CSS 101 (7 Part Series)
Now that we know how to use styles and select which elements we want the styles to be applied to, another important topic about CSS is the box model.
Yes, box model. The easiest way to imagine it is that every single element is inside of a box with multiple layers. These layers are margin, border, padding and content.
Let's talk about each of the parts of an element:
Content: The content box is where you'll see your content. This is what gets affected when you set an element's
Padding: The padding box is essentially an extension of the content box but the content itself leak onto the padding box. The thickness of the padding is added to the
heightof the content.
- Border: The border box wraps around the padding and content.
- Margin: The margin is a box encompassing all the boxes. This determines the amount of white space available between elements.
An alternative way to visualize the box model is to think of it like a property.
- Content: The house.
- Padding: The front/back yard and the narrow path between the house and the fence.
- Border: The fence surrounding the property.
- Margin: Possibly an alley, the sidewalk, or the road separating the house from the other properties.
We mentioned before that the padding adds to the width and height of the content. But what if you want to set the height and width of the element while taking padding and border width into account?
box-sizing is a CSS property that determines box model is handled for an element.
This is the default implementation.
Incorporates both the padding and border into the given width and height of the element.
padding-box previously existed but wasn't widely adopted and is now obsolete. More info about
So what should I use? Should I use
border-box? I don't have an answer for you but I prefer using
border-box. I prefer
border-box because it removes the uncertainties when sizing. It makes sure that if you set your element to have certain dimensions, it'll stay as such.
Now that we know the box model, we'll talk about specificity and cascade in the next post.
Level up every day