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: #cf9">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. IE7, meanwhile, actually hides much of the overflowing content. Hmmm.
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:
height: 80px