Understand CSS Layout with the Box Model

Tyler Clark
InstructorTyler Clark
Share this video with your friends

Social Share Links

Send Tweet

The box model is one of the most important aspects of understanding layouts and design. It defines how elements will be affected by margins, borders, padding, and actual content. Let’s use the google devtools to mess with different layouts.

Instructor: [0:00] The CSS box model is the foundation of layout on the web. Each element is represented as a rectangular box with the box's content, padding, border and margin built up around one another. As HTML is structured on the page, the browser will take this layering into effect when trying to piece together an overall layout.

[0:23] When we hover over our div here with a class of box, we see that it's 100 by 100. If we were to give it padding of 10 pixels and refresh, our box model accounts for this padding, and now, our width and height is 120 by 120. If we give this box a border of 10 pixels, solid and green, go ahead and refresh. Our box, it's even bigger now, as it accounts for border, and it's 140 by 140.

[0:50] If we add margin to this box of 10 pixels and refresh, we see that now we have margin on our box, but it's not actually affecting the size of our box. It's still 140 by 140. This is because margin acts a little bit differently. It surrounds a CSS box and pushes up against other CSS boxes around it in the layout, but it doesn't add to the height and width.

[1:12] If we wanted our browser to take into effect the height and width that we've given it and not add on padding and border to the height and width, we can do box-sizing -- border-box. This will tell it to not add in border and padding to the overall height and width, so we're back to 100 by 100. The default styling is not border-box but content-box.

[1:37] There is one caveat, however. Everything that we've seen so far with the box model only applies to block-level elements. If we were to add display -- inline here to our box -- we can see that height and width are going to be ignored.