CSS Box Model

CSS Box Model

·

3 min read

CSS box model refers to how HTML elements are tailored in browser engines. Guidelines for the box model are described by W3C(World Wide Web Consortium).

Almost the majority of HTML elements are considered to be boxed. These include div, paragraph tags etc. Each of these has five modifiable dimensions:

  • Width and Height: denotes the actual dimension of the content.

  • Padding: indicates the spacing between the content and the border.

  • Border: a line which is around the box.

  • Margin: indicates space around the border.

But why learn the box model? If you want to make a pixel-perfect website with high accuracy then we need this box model.

Width and Height

Width and Height of content are denoted in px, rem, percentage or em.

Padding

We use padding to put some space between contents. Padding is denoted in px, rem, percentage or em.

As you can see in the above snapshot, the menu items are so close that it's hard to distinguish each item. In these cases, we need to use padding between items.

Padding has four properties:

  • Padding-top

  • Padding-right

  • Padding-bottom

  • Padding-left

Shorthand for padding:

padding: 10px 5px 12px 8px

Border

The border is basically while making the buttons. The border has various CSS properties like:

  • Border-width: to specify the thickness of the border.

  • Border-radius: to specify rounded corners to elements. We can also specify which end we need border-radius. If we need it on all four sides we just specify it as border-radius: 5px with some values. If we need it on specific ends, we have options like Border-top-left-radius, Border-top-right-radius, Border-bottom-left-radius and Border-bottom-right-radius

  • Border-color: specify the colour of the border.

  • Border-style: dashed, solid, dotted, double, inset, outset, groove,ridge

Dotted Border

Dashed Border

Double Border

So, as we can see for the above items after adding a border, the items look so clumsy. Isn't it? So how do we separate them so they look separated from each other? That's when CSS property margin is used for.

Margin

Margin is used to separate elements from each other. It creates extra space around an element, unlike padding. Margin is denoted in px, rem, percentage or em. Takes both positive and negative values.

Margin has four properties:

  • Margin-top

  • Margin-right

  • Margin-bottom

  • Margin-left

Shorthand for Margin:

Margin: 10px 5px 12px 8px

Margin also takes negative values, unlike padding. ex: margin-top:-5px. This moves the element up by 5px; whereas margin-top:5px moves the element down by 5px. Now, the menu items are lined up correctly and are separated from each other by using the CSS box model properties.