The CSS Box Model

This tutorial is part of a web programming course for people who have no programming experience.


As you probably know by now, HTML elements are shaped as rectangles by default. We can use CSS to adjust the shape and dimensions of an element, and we can decorate them by doing such things as adding borders. Controlling the height and width of an element can sometimes be a little tricky because of the effects of various CSS properties.

<!DOCTYPE html>
<html>
    <head>
        <title>SAMPLE CODE - CSS Box Model</title>
        <style type="text/css">
            .sample{ background-color:lightgray; }
            div,span{
                /* MOST OF YOUR CSS CODE SAMPLES GO HERE */
            }

            /* SOME OF YOUR CSS CODE WILL GO HERE */
        </style>
    </head>
    <body>
        <h1>The CSS Box Model</h1>
         <div class="sample">Sample Div</div>
        <p>
            This paragraph contains a span tag inside <span class="sample">(span tags are inline elements)</span>of it.
        </p>
        <div id="some-div"></div>
    </body>
</html>

Before we begin, let's do a quick review of something we discussed way back when we learned about HTML. Remember that some HTML elements are block-level and others are inline. Block-level elements will stretch out and occupy the entire width of their parent element. On the other hand, inline elements occupy just enough width to accomdate their content. Inline elements will also fall inline side by side until they run out of space, at which time they'll wrap to the next line.

A DIV is a block-level element

A SPAN is an inline element Here is another SPAN element

Height and Width

You can set the height and width properties of a block-level element, but if you try do so for an inline element they will be ignored. Add these rules to to the ruleset in the STYLE element that targets DIV and SPAN elements:

height: 200px;
width: 300px;

When you reload the page you'll see the the height and width settings were applied to the DIV element, but ignored by the SPAN element.

In the above code sample, I've used px as the unit of measure, which is pixels. There are other units of measure as well (such as centimeters and inches), and we will see some of them shortly.

Borders

You can add borders to both block-level and inline elements. To do so you must specify the width of the border, it's color, and it's style (such as solid or dashed line). Add these rules to our sample ruleset and reload the page to see the borders appear:

border-width: 4px;
border-color: red;
border-style: solid;

There is short cut for setting all three of the above properties in a single line. You can simply set the 'border' like so (you can go ahead and add these right under the border settings from the above example as they will override any previous rules):

border: 2px dashed green;

They say that good programmers are lazy, and will therefore use as many syntax shortcuts as possible. So you'll often see this approach when you look at code written by other programmers.

You can change the borders for each side of an element by specifying it in the property name:

border-top-width: 5px;

Margin

You can add some space around the outside of an element by setting variations of the margin property:

margin-top: 30px;
margin-right: 30px;
margin-bottom: 30px;
margin-left: 30px;

Setting margins for block-level elements will work for all sides of the element. But top and bottom margin settings for inline elements will be ignored (probably because it would get messy when the elements wrapped from one line to the next).

There is a shortcut to set margins for all four sides of the element, just set the margin property and supply 4 values:

margin: 30px 25px 10px 5px;

The first number applies to the top, then the right side, then the bottom, and finally the left. I always remember this by starting at the top, and them moving clockwise.

If you want the margin on all four sides to be equal you can do this:

margin: 30px;

If you supply just two values for the property, the first one will apply to the top and bottom, and the second one will apply to the sides:

margin: 30px 10px;

Here's an old trick that you can use to horizontally center the text in a block-level element (for some darn reason, it can be challenging to center text in CSS!):

margin: 30px auto;

The top and bottom margin will be 30 pixels, and setting the sides to 'auto' will force the browser to measure the space available and divide it evenly on each side. One of the things that has made CSS tricky in the real world is that you needs to know about all sorts of tricks like this one to get things to look right. But there have been some new additions to the language recently have made things easier in some ways.

Padding

While margin is the space around the outside box of an HTML element, padding is the space inside the border. This example shows various ways to set padding:

/* Method 1 */
padding-top: 12px;
padding-right: 12px;
padding-bottom: 12px;
padding-left: 12px;

/* Method 2 */
padding: 30px 25px 10px 5px;

/* Method 3 */
padding: 15px;

The Display Property

You already know that in HTML some elements are block-level and others are inline. You can set the display property to change this for an element. The display property may be set to one of the following values:

  • block - This will make an element block-level
  • inline - This will make an element inline
  • none - This will hide an element
  • inline-block - The element will behave like an inline element, but will allow you to set it's height and width

You may be wondering why you would ever want to change the display property for an element, but as you'll see in upcoming lessons, it comes in handy sometimes. You can hide an element by setting it's display property to none and then use JavaScript code to make appear based on something the user does. The inline-block setting is a hybrid between block-level and inline. Using this setting for an element will make it remain inline, except that you can set it's height and width (recall that height and width settings for a fully inline element will be ignored). The inline-block setting comes in handy when you want to create horizontal nav bars, as you'll see in the worksheet that accompanies this lesson.

Go ahead and add this rule to the ruleset we've been working on:

display: inline-block;

When you reload the page, focus on the SPAN element that we've been targeting, and you'll see that it suddenly stops ignoring the height and width that we set for it earlier.

The True Height and Width of an Element

If you set the width of the an element, and then add a border, some padding, and margin, then the true width will be the combination of all of them. So you must be careful to account for padding, border, and margin when calculating the dimensions of your elements within a page. Add this code to the sample file, but make sure to put it after the ruleset that we've been working in for the previous examples. The DIV element that this ruleset targets is the last element inside the body of the sample page.

#some-div{
    width: 150px;
    border: 5px solid blue;
    padding: 10px;
    margin: 20px;
    background-color:gray;
    height: 75px;
}

Here's what the DIV would look like (note that the margin is a little hard to see because the background-color ends inside the border, but you can see it if you pay attention to the spacing outside the border of the element):

The true amount of space that the element will occupy is 220 pixels. The width is 150 pixels, there is 10 pixels for the border (5px on each side), 20 pixels of padding (10px on each side), and 40 pixels of margin (20px on each side). This is known as the CSS Box Model for calculating the true dimensions of an element. The problem with the box model is that you might spend a good deal of time measuring the elements that make up your page layout, making sure that the widths all total up properly. Then, when you get a little deeper into the page design and decide to add padding to an element to give it some 'breathing room', it will throw all your numbers off and you'll have to recalculate everything to fit within a certain amount of space.

The Box-Sizing Property

A relatively recent addition to CSS is the box-sizing property, which alleviates some of the head-aches of the box model. If you set the box-sizing property to border-box then the true width of the element will factor in the padding and border that has been applied. Let's add a rule to the previous ruleset that sets the box-sizing property to border-box:

box-sizing: border-box;

Now the DIV should look like this:

The width of the DIV appears to have shrunk, but that's because the 20px of padding (10px on each side) and the 10px of border (5px on each side) are now included in the width, thanks to the box-sizing property.

NEXT LESSON: Positioning Elements in CSS