SJHwebdesigns

Boxes

« Previous: Border, margins and padding | Next: display »

width and height

An element can be given a specific width and height by using the width and height properties (surprise!). These properties only work on block-level elements (but see below). For example:

#content {
     width: 760px;
     }

Avoid applying a width and height to an element unless you’re sure how much space its content is going to take up. If the element content is larger than can fit in the specified width and height, the content will overflow its container:

Code Output
<p style="width: 30px; height: 20px; background: #ccff99;">Whoops! I'm overflowing!</p>

Whoops! I'm overflowing!

At least it does in standards-compliant browsers. Versions of Internet Explorer prior to 7 will assume that you don't know what you're doing, and will extend the box to fit its content. This may seem like a help at first, but allowing content to overflow its container can actually be very useful, and also prevents the page layout from breaking on larger text sizes.

You can use the width property in combination with margins to create a fixed-width page which is centred in the browser window. Wrap the entire contents of the tag in a containing div, thus:

<body>
    <div id="container">
         the contents of your page go here...
    </div>
</body>

And then define the following styles for the containing div:

#container {
     width: 960px;
     margin: 0 auto;
     /* equivalent to margin-left: auto; margin-right: auto; */
}

Setting left and right margins to auto makes the container fit itself nicely to the centre of the page. 960 pixels is commonly used for fixed-width layouts at the time of writing, as this is the largest width that can fit easily into almost all screen sizes when scrollbars and other bits of browser chrome are taken into account.

The box model

When applying borders, margins and padding to an element with defined dimensions, you need to be aware of the box model, which defines how page elements should be displayed by graphical browsers. The box model states that the width and height specified for an element will define the size of the content area for that element; padding goes outside of this content area, borders go outside the padding, and margins go outside the border.

What is important to remember is that any padding, borders or margins are in addition to the width specified for the box. So a box with a width of 80px and padding of 40px on both sides would have a total width of 160px; adding a 40px margin and a 40px border would increase the total width to 320px:

margin: 40px
border-width: 40px
padding: 40px
width: 80px;
height: 80px
Total width: 320px

« Previous: Border, margins and padding | Next: display »

Page style: Dark Light