CSS boilerplate

December 17, 2022 - Reading time: 5 minutes

Here could be a CSS boilerplate for any project:

* {
margin: 0;
padding: 0;
box-sizing: border-box;
border: 1px solid orange;
font-family: sans-serif;
}

Explanations

Selector

Using * we are targeting all elements.

Properties

margin and padding properties set to 0 are for cancelling default browser margin and padding (see this previous article). Remember:

  • use margin to determine the space around an element (values: length (fixed value), percentage (relative value to the container's width), auto (decided by the browser, usually centers horizontally))
    • top and bottom margin don't apply to replaced elements (external objects) such as iframe, video, embed, img
    • older browsers may not support flexbox, so to center an element inside its parent, also use
      margin: 0 auto;
  • use padding to determine the space inside an element (values: length or percentage)

box-sizing property is new to me. It sets how the total width and height of an element is calculated (this explanation and others as well are from MDN Web docs, completed by W3Schools): it can be either unrestricted or restricted to the parent's container.

    • default value is content-box. The calculation is:
      • element's width = witdh + padding + border
      • element's height = height + padding + border

      For instance,
      .box {
        width: 350px; 
        border: 10px solid black;
      }

      renders a box that is 350 (box width) + 10 (right border ) +10 (left border) = 370px wide.

      This means that you may have elements sharing a same width and height but if they have different paddings and/or borders, their total size will be different.

    • the other possible value for box-sizing property is border-box. This changes the calculation to:
      • element's width = witdh
      • element's height = height

      In other words, padding and border are included in the total width and height:
      .box {
        width: 350px; 
        border: 10px solid black;
      }
      renders a box that is 350px wide. This makes the world a little easier to live in, dosen't it?

border property to debug positioning drama - you should of course delete or comment (just in case haha) this line for going-live and chose a good contrasting color . I confess, when it comes to add some CSS I often feel not knowing why it's not behaving as expected. So just like many fellows, I'm adding borders to elements and yes, it helps a lot. To avoid repeating it, I put it inside the all selector (*).

font-family property to sans-serif just to make a first step out of raw HTML, it's totally subjective.