Get hold of THE CSS BOX MODEL

Get hold of THE CSS BOX  MODEL

Boxes are something you need to be familiar with while working with CSS. Because they are everywhere, everything in CSS is a box whether it be a square or a rectangle. So learning how to manage, structure, and design the Box is one of the fundamentals in CSS.

The CSS box model is a box that wraps the HTML elements. The CSS box consists of four parts and they are :

  1. Content

  2. Padding

  3. Border

  4. Margin

Let's take a look at all of them through a diagram

2.PNG

In the diagram the blue-colored area in the center is the content, then the area between the border and the content is the padding, and the area covering the border is the margin.

Padding

Padding is used to increase space around the content and is declared as:

.box{
   padding:10px;
}

This will add padding to all the sides of the content we can also apply padding to the desired side by adding the top, bottom, right, and left followed by a hyphen.

Margin

Margin is used to define the space between the elements and is declared as:

.box{
   margin:10px;
}

Similar to padding, this will add margin to all the sides of the element we can also apply margin to the desired side by adding the top, bottom, right, and left followed by a hyphen.

One interesting case arises when we have two margins collapse over each other, Let's take an example

HTML Code

<div class="box-one">Box One</div>
<div class="box-two">Box two</div>

CSS Code

.box-one {
  margin-bottom: 20px;
}
.box-two {
  margin-top: 10px;
}

So what do you think the distance between box-one and box-two will be? If you added the margins you're wrong, as when margins collapse the margin which has the greater value is considered.

Border

The border is the line that wraps the content and the padding area(fill-area), now border can be declared in many ways but the shorthand way of doing it is

.box-one{
    border: 5px solid #000;
}

We define the width, the type, and the color of the Border. Similarly, you can also assign borders to the sides.

Height and width

We have height and width properties in CSS but that does not determine the size of the whole element but it only determines only the content size.

So the actual width of the element would be (width) + (left + right padding) + (left + right border) + (left + right margin)

And the actual height would be (height) + (top + bottom padding) + (top + bottom border) + (top + bottom margin)

Solution

But what if we want to have the height and width as the whole element's height and width. In that case we need to simply set the box-sizing as border-box.

*{
    box-sizing:border-box;
}

It is a nice practice to write define this in the Univeral selector.

🙏Thank you for reading this and I hope it helped you in your CSS journey.

✔Follow my Twitter handle and let's Connect