DEV Community

Karl Castillo
Karl Castillo

Posted on • Updated on

CSS: Box Model

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.

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.

Box Model Diagram

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 width and height.
  • 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 width and height of 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.

I'm still confused...

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.

The alternative box model?

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

box-sizing is a CSS property that determines box model is handled for an element.

content-box

This is the default implementation.

border-box

Incorporates both the padding and border into the given width and height of the element.

ASIDE: padding-box previously existed but wasn't widely adopted and is now obsolete. More info about padding-box usability.

What now?

So what should I use? Should I use content-box or 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.

Latest comments (1)

Collapse
 
jlrxt profile image
Jose Luis Ramos T.

Gracias.