Pitch your project

Random text


By admin Category Uncategorized, Posted February 12th, 2016
The CSS Box Model and Box-sizing

When I first started to work with HTML and CSS I always had problems understanding what u really could do with the box model in CSS. With this blog I will try and explain the basic information so u know more about the subject.

The box model and box-sizing are two very importent subjects in web developement, they are both very essential if you want to understand page layout and other web design issues, lets start with the box model.

CSS Box Model

In a document, each element is represented as a rectangular box. Determining the size, properties like its color, background and borders aspect.
A box model applies to all HTML elements. It defines how a box and its attributes relate to each other. It is essentially a box that wraps around every HTML element. It consists of: margins, borders, padding, and content.

  • Margin – Clears an area outside the border. The margin is transparent
  • Border – A border that goes around the padding and content
  • Padding – Clears an area around the content. The padding is transparent
  • Content – The content of the box, where text and images appear

alt text

I will show u a simple example where two boxes with the same width end up with different sizes.

.small {
  width: 300px;
  margin: 30px auto;
  border: 5px solid #000000;

.big {
  width: 300px;
  margin: 30px auto;
  padding: 40px;
  border: 5px solid #000000;

alt text

When I was working with CSS and using the box model, I sometimes use a smaller width than what I want, subtracting out the padding and border. Thankfully, I don’t have to do that anymore.

CSS Box-sizing

Since the beginning of CSS, the box model has worked like this:

  • width + padding + border = actual visible/rendered width of an element’s box
  • height + padding + border = actual visible/rendered height of an element’s box

Unfortunate this is counter-intuitive, because the width and height you set for an element both go out the window when you start adding padding and / or borders to the element.

The box-sizing property has 4 values:

  • content-box
  • border-box
  • initial
  • inherit

The most popular and used value is border-box, what does it do? The width and height properties (and min/max properties) includes content, padding and border, but not the margin.

Let me show you an example of box-sizing:

.container {
    width: 30em;
    border: 10px solid red;

.box {
    box-sizing: border-box;
    width: 50%;
    border: 10px solid blue;
    float: left;

div.clear {
    <div class="container">
      <div class="box">This div occupies the left half.</div>
      <div class="box">This div occupies the right half.</div>
      <div class="clear"></div>

alt text

If u want to try the box-sizing yourself I suggest u go to this link.

Posted by Eelco Poelstra

Leave a Reply

Your email address will not be published. Required fields are marked *