Professional Innovations

November 20th 2014 / CSS

CSS Box Model

Posted by Alain Francis

In this article we will be covering the most important concept in CSS, THE BOX MODEL, which includes the major CSS properties:

  • Margins
  • Borders
  • Paddings
  • Width
  • Height
  • Float properties
  • Box-sizing CSS 3 property

Every HTML element is considered as a box, the box model is used when talking aboud design and layout.

box_model.jpg

  • The content is the actual HTML content where text and images appear;
  • The padding is the space between the content and the border;
  • The border goes around the padding and the content;
  • The margin is the space between two # elements, it's outside the border area.

The 4 points listed above constitue the box model, and are part of the WIDTH  and HEIGHT properties.

To calculate the actual width of an element, we have to add all the above properties to the actual content.

For example, consider having a div that has a width of 100px, with a padding of 10px and a border of 2px, the actual width would be: 100px + 20px(left and right padding) + 4px(left and right border) = 124px;

The margin property also plays a part in the width property, consider having the below example:
We have two div's of 50% width each, and a float:left property set to both to have them sit near each other. Adding a margin-left to any of the div's will lead to a breaking which will set each one on it's own row.

The same concept of calculation applies to the height property.

CSS3 has introduced a new property which will override the above concept, the Box-sizing property will let you include the margin, border, padding in the actual content width.

So if we use the same example with the below CSS property:
box-sizing: border-box;

Our width will stay set to 100px, but the margin, border and padding total will be deducted from the content width, which means that the content would be 100px - 20px - 4px = 76px

Now let's talk about the float property.

HTML elements differ from each other in the display property. Some of them have a display set to block while others have it set to inline.

What is  the difference between an inline and block element?

Inline elements are elements that sit near each other without breaking, like the <span> element and the image element, the <b> and <em> elements.
Block elements are elements that insert a break line before and after them, like the <div> elment and the <p> element, so each one will be placed on its own row.

The default float value of an HTML element is set to :none. To be able to place two elements with a display set to block, we have to change that value to left or right; this will work on one condition, having a parent element with a width that completely fits the two elements width.