CSS Box Model for Beginner: Unlocking the Magic of CSS

Written by afiur.fahim | Published 2017/06/16
Tech Story Tags: css | web-development | technology | web-design | coding

TLDRvia the TL;DR App

If anyone ever asked me, what is the ONE thing I need to understand to master CSS or designing a page layout, I wouldn’t take a second to answer: The box model, The building block of CSS. I hope, now you know how important it is. If you’re a beginner at CSS, take your time to master the concept of CSS box model before proceeding further. It’s not hard, but it’s a little bit tricky. Bear with me!

The World is made of Boxes!

On a web page, we may see every possible real-world shape. But would you believe me if I told you that everything you see on a web page is a rectangle? Well, believe me or not, it is!

Let me repeat: Everything you see on the web is a rectangle. You need to remember this while designing just as much you need to remember to breathe while you’re sleeping. Don’t worry if my metaphor doesn’t make sense, the box model will.

Structure of CSS Box Model

So, every piece of content on a web page, or in other words, every HTML element is formed by a rectangle. Each of these rectangles has 5 main aspects that it's built around. They are:

  • Width
  • Height
  • Padding
  • Border
  • Margin

All of these five aspects determine the size, position, and presentation of an element. Thanks to CSS, we can control all of these to make an element appear on a web page exactly the way we want. So, let’s try to understand each of the them.

Level of Element

Basic understanding of the HTML element level is required to understand the CSS box model. I’ve discussed HTML inline-level and block-level element recently in a post. For a refresher, block-level content is what takes up all the horizontal space it gets, no matter how much its content actually needs. On the other hand, inline level elements are those that take up only the space its content needs to fit in. Refer to the post for a detailed explanation.

For its nature, inline-level element deals with some of the aspects of box model a little differently than block-level element. I’ll mention these exceptions along the way. So, pay attention to that.

The Width

The width is simply the width of an element, the amount of space an element takes from left to right. By default, the width of a block-level element is 100% of its container. For inline-level element, the default width is how much it’s content needs.

CSS box-model — Width

We can control the width of an element using the CSS width property. But keep in mind that, since inline element doesn’t have any predetermined width (because it’s width is determined by its content), it’s not possible to set a fixed width on those elements. Hence, the inline element doesn’t accept the CSS width property.

However, we can overcome this limitation by changing the type of element, which we’ll discuss at the end of this post. For now, just know that inline element normally doesn’t support the CSS width properties.

Okay code time, let’s see the width property in action.

<!DOCTYPE html>

<html>

<head>

<title>CSS Box Model</title>

<link rel=”stylesheet” type=”text/css” href=”style.css”>

</head>

<body>

<div class=”box”>&nbsp;</div>

</body>

</html>

So, I’ve created a very simple HTML page with only one div element. div is a block-level element. So it’ll support all the CSS properties of box model.

Note: This is an empty div. I have added a non-breaking space ( ) inside the div because divs don’t show up on the page unless they have content. But essentially, it’s empty.

As a block-level element, this div has a width of 100% by default. To make it visible to the eye, I’m going to add a background color to it.

.box {

background-color: darkviolet;

}

It looks like this in the browser:

Default width of an element

The div element is taking up all the space from left to right. Now, let’s override the width with just as much width as we want. We can specify the width in CSS using several units such as pixel, percentages etc. We’ll use pixel (px) here since that’s the most used one.

.box {

width: 200px;

background-color: darkviolet;

}

So, we’ve simply declared the width we want using CSS **width** property. Let’s take a look at our element now.

Custom width of an element

Boom! Now our element isn’t taking up the entire horizontal space. It’s only taking as much as we’ve specified. This way, we can create elements of the exact size we wish.

The Height

Just like width, height is also the size of an element, but in the vertical direction. The div that we created have a height of one character. Because we technically have a character in it.

CSS box-model — Height

In both block-level and inline-level element, the height of an element is determined by element’s content. Height automatically adjusts to make room for the content. But of course, we can specify the height of any element exactly as much as we want using the CSS **height** property.

.box {

width: 200px;

height: 200px;

background-color: darkviolet;

}

On that same div, we have applied a height of 200px. Now it should be a lot taller than it was last time. Let’s take a look!

Custom height of an element

Yep, our box is now a perfect rectangle. So, we can obtain elements of literally any size by using the **width** and **height** property together.

But please do take note that, CSS **height** property, for the same reason as width, can not be applied to an inline-level element.

The Border

Border means just as the words describes. It lets us put a border around our main content. It’s optional. But even though you may or may not have a border, according to CSS box model, every single element still have a border. You’re not using any border just means that the border value of your element is zero.

CSS box-model — Border

We can specify border using the CSS **border** property. This property needs three values to display border properly. They are: The width of the border, style of the border and the color of the border.

Width can be any size in pixel. Style determines the visual presentation of a border. It can be one of solid, dashed, dotted, double etc. Try them out and use them according to your relevance. And lastly, we need to set a color of the border.

So, let’s apply a border on our div and see how it looks.

.box {

width: 200px;

height: 200px;

background-color: darkviolet;

border: 5px solid hotpink;

}

Output:

Element with border applied on it

Our 5px border around the box looks great! The border property offers us a lot of customizability. We can specify border style, size, color on each side of the box. But that a topic for another day.

The Padding

Padding is the space between your content and border. You can have your border at a distant place from your main element. While this may not sound like something very useful, but it actually is.

CSS box-model — Padding

Padding plays important roles in the visual design of elements. They make content easily understandable to the users. They also help to create space between elements. We can specify padding using the CSS **padding** property.

Let’s apply some padding on our box to make this concept clear.

.box {

width: 200px;

height: 200px;

background-color: darkviolet;

border: 5px solid hotpink;

padding: 25px;

}

So, we have applied 25px padding all around our content. How might this look?

Element with padding

Nope I haven’t included the wrong screen shot. This is how it looks now. Confusing? Don’t let yourself be! Even though it looks exactly the same as (except a little bit bigger now) when it didn’t have any padding, but it actually not the same.

It has 25px of space between the box and the border on every side. But it’s not visible because the nature of padding is that it adopts color from its parent’s background color. And that is why the padding is not visible.

Padding itself doesn’t have any color and isn’t possible to apply any color on padding space specifically. It always inherits color from its parent. To illustrate this little tricky thing, I’m going to put some text into our box and then take a look at it again!

Padding (with text inside the box)

Now, do you see those empty space between the text and the border? That is our padding. And that’s exactly 25px as we’ve specified. Wonder how it’d look like without the padding? Here you go:

Padding removed

See no space between border and text! Hope it clarifies your confusions. We can apply different amounts of padding on different sides by using padding-left, padding-top, padding-right, padding-bottom CSS property too.

Padding can be applied on all four sides of inline elements too. However, top and bottom padding on inline element might bleed into other elements. So be careful with that.

The Margin

The last and most troublesome aspect of CSS box model is the margin. But you’ve nailed it there understanding all other four aspects. Killing the fifth boss after killing other four is nothing but more exciting! Ever played House of the Death? ;)

Anyway, Margin is the reserved space outside of an element’s border. Or, you could also say it like this: Margin is the space between different elements. That is, if you have a certain space declared as a margin of your element, no other element can sit in that space. Even though this space is situated outside of your element.

CSS box-model — Margin

Margin is very important in terms of creating a page layout, positioning element and creating whitespace between elements. To demonstrate margin, I’m going to make a copy of our existing div and place the new one beside the old one with some margin in between.

CSS for both div:

.box {

width: 200px;

height: 200px;

background-color: darkviolet;

border: 5px solid hotpink;

padding: 25px;

margin: 20px;

}

And the output is:

Two boxes with margin in between

What if I didn’t have the margin? This:

Two box without margin inbetween

Notice that there is no space between two boxes. But when we had margin, it created 20px space on all four side of the box. We can also apply a different amount of margin on different sides using the margin-left, margin-top, margin-right, margin-bottom properties.

For inline elements, the margin can only be applied on left and right side of the elements. Inline-level elements don’t support margin on top and bottom.

So that is the box model. I know, all those figure and screenshots caused a little extra load time and consumed some extra bytes of your data, but I really hope they helped you understand the key concepts.

Two CSS Magic Wand

Now that you know what CSS box model is and understand all of its key aspects, but you’re not done yet. For leveraging its power to the fullest, You need to know how the measurement of the boxes or, elements work. Otherwise, it may cause you a headache as you’d be trying to figure out why your element doesn’t stay in place and breaks the layout.

Bear with me, this will be short and sweet.

The Measurement

Take a look at the CSS code we used on our box element once again. Now tell me what’s the width of the box? 200px, right? Nope, WRONG. Even Though we’ve specified 200px as the width of our box, the actual width of the box is much different. The formula of calculation is this:

Total width = Margin left + Border left + Padding left + Content Width + Padding right + Border right + Margin right

We have 20px of margin, 5px border and 25px of padding on both side of our box. Let’s calculate the width of our box according to the formula:

Total width = 20px + 5px + 25px + 200px + 25px + 5px + 20px

= 300px.

That’s an extra of 100px! When creating elements based on available space on a web page, you have to be really careful about the measurement of your element unless you want to end up stretching your own hair. The calculator is your old friend.

Does doing the math for every single of your element sounds too complex? Let me introduce you to the first CSS magic wand!

The **box-sizing** Property

CSS3 introduced a new property named box-sizing which lets us change how the width of the element is measured. It supports two different value. They are:

  • content-box
  • border-box

Content box is the default one that we’ve discussed. If you change your element’s box-sizing to border-box, then the size you specify as your element’s width will include the space of your border too.

For example, let’s take our box. We have a specified width of 200px. When we are adding 25px of padding on both side, it’s becoming 250px. But if we use border-box, then the added width of the box and it’s padding together will be 200px.

In that case, the width of our main content will be 150px and the rest of the 50px will be our padding. And if we change the size of our padding, the width of our content will be changed automatically to accommodate the padding within the specified width.

As you might’ve already understood, the border-box sizing property can make our life so much easier than the times when everyone had to use a calculator to create their elements.

CSS Display Property

The last one important CSS property we’ll discuss today, which is known be an ‘Aha’ find to a lot of beginners is the display property. All the elements of a web page are rendered by the browsers depending on their display types. Guess what the element display types are? The same old inline and block-level elements that you already know.

What’s so cool about the display property? The cool part is that it lets you convert the display types of any element. Which means you can turn a block-level element into an inline-level element and vice versa! Plus, you can convert them into a special type called inline-block.

The inline-block property can turn any inline or block-level element into an element that shows the behavior of inline-level content, but they support every single aspect of the CSS box model. The inline-block property offers us efficiency of inline element and the customizability power of the block-level element, which makes it our second CSS magic wand.

Think about it for a moment. Almost all the behavior of any given element mostly depends on its display type. That you can change an element’s display type means you can literally tweak everything about that element. Isn’t it so empowering that you have pixel-perfect control over all the aspects of an element? You can build anything! Imagination is the only limit.

Recap

So, now you’re all set to master every other concept of CSS. Before you leave, let’s make sure you’ve grasped the main ideas.

  • Every single element we see online is essentially a rectangular box.
  • These boxes have five main aspects. Which are width, height, padding, border, and margin.
  • By changing these aspects via CSS, we can turn any element into any sizes and any shapes imaginable.
  • The default measurement system of element is a little tricky. But we can turn it mostly into our favor by using a magic wand called border-box and say goodbye to calculator.
  • We have to keep in mind that inline element normally doesn’t support tweaking some of the aspects of box model. We can convert them into block or inline-block element and then do whatever we want to! We are the king!

Modern neuroscience has discovered that analogy and recalling are two of the most effective ways to learn new things the best way. With that in mind, I’ve stolen this picture from google images for you to practice on CSS box model.

Look at the image closely. It’s a real life analogy for CSS box model. It has all the aspects that CSS box model has. Try to recall the concepts and find out the aspects of box model in the image. Then explain to me how they are related to each other in the comments.

A real life analogy of CSS box model

Conclusion

Thanks for staying with me until the end. I hope it was worth your time. I am a beginner myself and I know how it feels when nothing seems to make sense. Don’t be upset if you didn’t understand everything about CSS box model. Try to create something, read this again, do a lot of mistakes and eventually, everything will start to make sense.

The box model is the building block of CSS. Which is why I felt the necessity to invest my time and effort to put this together so that you can get the highest benefit possible from one article. If you found any value from this post, please click on the heart below to show some love.

I’m on a journey to learning web development and I write about everything I learn here on Medium and on UX Art. You can join me on this journey here. Feel free to poke me on Twitter!


Published by HackerNoon on 2017/06/16