Hour 6. The CSS Box Model

wax ka badal
What You'll Learn in This Hour
  • How web content is displayed visually in CSS as boxes
  • What categories of display elements are used and how you can affect an element's display type
  • How CSS browsers interpret and display web pages
  • How to set margins, borders, and padding on a box

This hour explores the core of Cascading Style Sheetsthe part of the specification that defines how parts of a web page are displayed: as stacks of boxes. The visual presentation of CSS is defined as a series of boxes based on the structure of the original document. |}

./ ADD NAME=CH06LEV1SEC1.HTML

Displaying Content in CSS

wax ka badal

The content of a web page is the information encoded within the HTML page, found between the opening and closing tags of the HTML markup. These tags define the structure of the content, a framework that gives meaning to the content. For example, consider the following HTML:

<p>This is the <strong>tricky part</strong>,
 so pay attention!</p>

The content in this example is simply the sentence This is the tricky part, so pay attention! The tags embedded within (and surrounding) the content create the structure, which gives meaning to the content. Any browser that understands HTML knows that the whole thing is a paragraph (identified by the

tag) and that the phrase TRicky part is strongly emphasized. The presentation of the content, however, is not defined by the HTML; instead, it's determined by CSS rules. The browser has default rules for

and tags, which say that a

is shown visually as a paragraph on lines of its own, with leading and trailing space, and that the is shown as bold text within that paragraph. Both the

and tags are shown as display boxes, which is how CSS browsers deal with HTML elements. Each HTML element corresponds to a display box, although not all elements are shown on the screen. A display box is a rectangular shape on the screen that can contain text content, images, form controls, or other display boxes. The exact method by which HTML elements are shown as CSS display boxes is called the visual formatting method. The visual formatting method tells browsers how they should show HTML content on the screen. Types of Elements In the visual formatting model, markup elements are classified into two basic typesblock and inline. The type of element determines how CSS browsers will display instances of that element. The initial type of each HTML element is set by the HTML specification. For example,

tags are block elements, and tags are inline elements. The full list is given in the HTML 4.01 Recommendation; each tag has an indication as to what type it is. You can change the type of a specific element with CSS, although often you won't need to. Certain CSS properties can be set only on block or inline elements; for example, the text-indent property (which you'll learn about in [file:///C:/Documents%20and%20Settings/dani/Asztal/Sams%20Teach%20Yourself%20CSS%20in%2024%20Hours_2ndEd/0672329069/ch15.html#ch15 Hour 15], "Alignment") applies only to block elements. Block A block element is one that is intended to be displayed as a distinct block of content, starting and ending with a new line. Besides the

tag, other block elements in HTML include

,

,

, ,
    , and the

    to

    tags.

    Block elements are listed one after each other, vertically down the page. They are as wide as they can be, which means that unless they're constrained in some way (by other block elements, by CSS properties, or by HTML markup), they'll stretch across the whole page.

    Did you Know? One thing you'll notice when you start using CSS is that your headers (

    and friends) go all the way across the screen. Set the background-color property on an

    and you'll see how big it really is.

    Inline

    An inline element doesn't begin and end lines; instead, it is contained within the flow of the text. Examples of inline tags include , , , <img>, <input>, and <a>.

    Inline elements flow one after another in a line, with no line breaks, horizontally across the page until the end of the available space is used up; then they just continue where they left off on the next line down.

    The display Property

    You can change the type of an element by using the display property. This property can take several values; the ones we're primarily concerned with in this hour are block and inline. There's another important value for display that's called none; something that has the display property set to none does not display at all, nor is anything inside of it displayed.

    Setting the display property to block or inline changes the type of that element to the specified type. For example, imagine that you want to make a navigation menu, and you want all your <a> elements within that menu to appear as block elements. The HTML code may look like this:

    <div class="nav">
     <a href="friends.html">My Friends</a>
     <a href="cat.html">My Cat</a>
     <a href="friendscats.html">My Friends' Cats</a>
     <a href="catsfriends.html">My Cat's Friends</a>
    </div>
    

    The <a> element is an inline element according to the HTML 4.01 specification, so by default browsers display these links as a row all on the same line, or maybe wrapping around to the next line down if there is no more room. To display these <a> tags as block tags, use this rule:

    .nav a { display: block; }
    

    [file:///C:/Documents%20and%20Settings/dani/Asztal/Sams%20Teach%20Yourself%20CSS%20in%2024%20Hours_2ndEd/0672329069/ch.htm#ch06fig01 Figure 6.1] shows the effect of applying this rule; the first set of links is identical to the second, except that the previous rule and a silver background have been applied to it. The background illustrates that the block element goes all the way across the browser window and doesn't stop at the end of the text within it. Also, the links are clickable even on the far right side of the screen, not just on the blue underlined words.

    Figure 6.1. Before and after redefining the <a> links as block.
    [file:///C:/Documents%20and%20Settings/dani/Asztal/Sams%20Teach%20Yourself%20CSS%20in%2024%20Hours_2ndEd/0672329069/images/06fig01_alt.jpg [View full size image]]
    File:06fig01.jpg

    ./ ADD NAME=CH06LEV1SEC2.HTML

    Understanding the Box Model

    Within the visual formatting model, all elements generate specific types of boxes. The method for displaying these boxes is called the box model, and understanding the box model is crucial for understanding how Cascading Style Sheets will display web pages.

    The box model is defined in terms of elements, documents, trees, and of course, boxes. Many of us are not used to thinking about web pages in terms of these elements unless we've done a lot with XML or SGML. So you first need to understand the assumptions that CSS makes about web documents.

    By the Way In formal W3C specifications, you rarely see terms such as web page; instead everything talks about documents. Likewise, you don't see much about tags and browsers, but instead elements and user agents. Although it may seem that this is just semantic snobbishnessand to some degree it is!there are actually some valid reasons for drawing these distinctions when speaking formally. In this book, I try to avoid writing text like you'd see in a W3C Recommendation; if you want one of those, you can find it on the W3C site at http://www.w3.org/. However, terminology counts for this discussion, and my apologies if I sound formal.

    Documents as Trees

    Did you know that every web page is actually a tree of tags and content? If you didn't, that's okay; these types of trees are the same kind of data structures used in computer science, and most web developers aren't necessarily computer scientists.

    A tree is a way of representing information in a hierarchy of elements. Think of it as somewhat similar to a family tree in genealogyone that starts at a certain ancestor and goes down from there. Your great-grandmother may be at the top; her children (including your grandmother) in the second level down; your mother, her siblings, and her cousins in the third level down; and you and the other members of your generation in the fourth level.

    In the same way, an HTML document can be thought of as a tree with the <html> element as the top. In this context, the <html> element is known as the root element.

    The <html> element has two children: the <head> and the <body>. These are shown lower on the treethe next levels down. The <head> has children too; <title> is one in every document, and <link> may be there to call in an external style sheet. The <body> element contains the content of the page; this could be anything from

    and


to

or
. Some of those may have their own children, and some may not.

Each part of a tree is called a node. A node is either an element (possibly with children) or some text. Text nodes can't have children; they're just text.

[file:///C:/Documents%20and%20Settings/dani/Asztal/Sams%20Teach%20Yourself%20CSS%20in%2024%20Hours_2ndEd/0672329069/ch.htm#ch06ex01 Listing 6.1] shows a very simple web page, and [file:///C:/Documents%20and%20Settings/dani/Asztal/Sams%20Teach%20Yourself%20CSS%20in%2024%20Hours_2ndEd/0672329069/ch.htm#ch06fig02 Figure 6.2] shows a representation of a tree based on that page.

Listing 6.1. The First Two Lines of a Poem About Trees

<html><br /><head><br /><title>Trees</title><br /></head><br /><body><br /><h1>Trees, by <i>Joyce Kilmer</i></h1><br /><p><br />I think that I shall never see<br /><br><br />A poem as lovely as a tree.<br /></p><br /></body><br /></html><br />

Figure 6.2. Our poem represented as a tree.

File:06fig02.jpg

Documents as Boxes

After an HTML document has been defined as a data tree, it can then be visually interpreted as a series of boxes. This is probably an easier way for web developers to think of a page, but it's important to reach that understanding by first visualizing a tree because that's how a CSS browser considers the page.

You can think of these boxes as containers that hold other boxes or that hold text values. Each box in the CSS box model is held within another box, except for the box corresponding to the root node in the tree. The outer box is called the containing box. A block-containing box can hold other block boxes or inline boxes; an inline-containing box can hold only inline boxes.

In [file:///C:/Documents%20and%20Settings/dani/Asztal/Sams%20Teach%20Yourself%20CSS%20in%2024%20Hours_2ndEd/0672329069/ch.htm#ch06fig03 Figure 6.3], you can see the tree poem expressed as a series of nested boxes. You'll notice that some of these boxes don't have labels; a box exists, but no HTML tag! Those boxes are known as anonymous boxes. Anonymous boxes result whenever a tag contains mixed contentboth text and some HTML tags. The text parts become anonymous boxes. An anonymous box is styled the same as its containing box.

Figure 6.3. The tree poem as nested boxes.

File:06fig03.jpg

Also notice that the
tag is an empty tag; it doesn't contain any content, but it still generates a box. The <head> box appears in [file:///C:/Documents%20and%20Settings/dani/Asztal/Sams%20Teach%20Yourself%20CSS%20in%2024%20Hours_2ndEd/0672329069/ch.htm#ch06fig03 Figure 6.3], but in HTML the <head> tag is defined as display: none;; this is why you never see the content of the <head> tag.

./ ADD NAME=CH06LEV1SEC3.HTML

Box Display Properties

After a browser has established that a box exists by building a tree as shown earlier and then by filling in the box model; it displays that box, either according to its own internal rules for displaying HTML or according to the style properties on that box.

In a way, all the CSS properties are box-display properties: They control how a box is displayed. However, three properties define the edges of that box: the margin, the border, and the padding.

The relationship between margin, border, padding, and the content itself is shown in [file:///C:/Documents%20and%20Settings/dani/Asztal/Sams%20Teach%20Yourself%20CSS%20in%2024%20Hours_2ndEd/0672329069/ch.htm#ch06fig04 Figure 6.4]. In this example, the border color has been set to gray and the background-color to silver.

Figure 6.4. The margin, border, padding, and content of a box.

File:06fig04.jpg

By the Way You'll learn more about the margin, border, and padding properties in [file:///C:/Documents%20and%20Settings/dani/Asztal/Sams%20Teach%20Yourself%20CSS%20in%2024%20Hours_2ndEd/0672329069/ch16.html#ch16 Hour 16], "Borders and Boxes;" the current hour is a general introduction to the box model, and we'll get into more detail about other property values later in the book.

The margin Property

The margin is an invisible property that surrounds all CSS boxes; it dictates how far that box is from other boxes. The margin is the outermost property of the box and defines the far edge of the box. Nearly all of the visible HTML elements have margins, although for many the default margin is 0 pixels.

Values for margin can be expressed in a variety of units; the most common values are pixels or ems. A pixel is the width of a single dot on the screen; pixel values are written as a number followed by px, such as 4px or 12px. An em is unit of measure that refers to the size of the current font; if the font is 12 pixels, an em is a unit of measure equal to 12 pixels. You write ems by putting the word em after a number, such as 3em or 0.5em.

Pixels are absolute units; they do not scale with the user's preferences. Ems are relative units; relative units are calculated based on the current font. Other units you can use include points (pt), centimeters (cm), inches (in), and percentages.

To set a margin of 1 em around a specific box, such as an

, you'd write a CSS rule like this:
h1 { margin: 1em; }

Margins are always transparent, meaning that whatever background color is set on the containing box shines through.

There's one more thing you need to know about margins, and that's collapsing margins. The vertical marginsthose above and below the elementdo something called collapsing, which means that only the largest value of the margins between two elements is used. Margins collapse only on block elements and only in a vertical direction, not horizontally.

Did you Know? One way to think of the collapse of margins is to imagine two motor homes parked next to each other. The owner of the motor home to the north says to the other, "Don't park within six feet of me." The owner of the southern motor home says, "Don't park within three feet of me." How close together can you park the motor homes, assuming you want to get them as close as you can? Obviously, you would park six feet away; that distance fits both requirements. That's what a margin value is like; you take the largest value of the two and use that as the vertical distance between two elements.

The border Property

The border property is used to draw a border around a box. All boxes have borders, even if the size of the border is 0 pixels or ems, which is the default for HTML elements.

Each border has three qualities associated with it, which can all be set with the border property: the size of the border, the style of the border, and the color of the border. A border declaration reads like this:

selector { border: size style color; }

The size of the border is measured the same way as the margin; pixels or ems are the most common units. Border styles include solid, dashed, and dotted; you'll use more border styles in [file:///C:/Documents%20and%20Settings/dani/Asztal/Sams%20Teach%20Yourself%20CSS%20in%2024%20Hours_2ndEd/0672329069/ch16.html#ch16 Hour 16]. The color of a border can be any CSS color name or RGB triplet.

So, to set a solid navy blue border that is 1/4 of the current font size around an

, you would write a rule like this:
h1 { border: 0.25em solid navy; }

And here's a dashed three-pixel purple border around paragraphs:

p { border: 3px dashed #660099; }

You can set borders (and margins and padding) around inline elements as well as block elements. This sets a thin black border around tags:

i { border: 1px solid black; }

The padding Property

The space surrounding the content is the padding; this could be thought of as whitespace because there's nothing in it (no content or border), but keep in mind that it doesn't have to be white. The padding is always the same background color as the content itself, which means it is the color of the background-color set on the box.

Padding is measured in the same way as margins or borders; here's a three-pixel padding around and a padding of 0.5 em around

:
i { padding: 3px; }
h1 { padding: 0.5em; }

Want to see the result of all the examples discussed so far? [file:///C:/Documents%20and%20Settings/dani/Asztal/Sams%20Teach%20Yourself%20CSS%20in%2024%20Hours_2ndEd/0672329069/ch.htm#ch06fig05 Figure 6.5] shows what happens if you apply all the CSS rules named, including margin, border, and padding, to the poem from [file:///C:/Documents%20and%20Settings/dani/Asztal/Sams%20Teach%20Yourself%20CSS%20in%2024%20Hours_2ndEd/0672329069/ch06lev1sec2.html#ch06ex01 Listing 6.1]. I added a <style> section in the <head> and included these rules as an embedded style sheet.

Figure 6.5. Applying various box styles to the tree poem, as shown in Firefox.
[file:///C:/Documents%20and%20Settings/dani/Asztal/Sams%20Teach%20Yourself%20CSS%20in%2024%20Hours_2ndEd/0672329069/images/06fig05_alt.jpg [View full size image]]
File:06fig05.jpg

./ ADD NAME=CH06LEV1SEC4.HTML

Summary

The visual formatting model of CSS describes how pages should be displayed. An HTML (or XML) element can be block or inline, and the display property can change how an element is displayed.

The box model views web pages as nested boxes based on a tree view of a web document. Web pages are displayed as CSS properties set on those boxes.

The margin, border, and padding properties define the outer edge of the box. Margins are transparent and surround the box, separating it from other boxes; vertical borders collapse to the largest value. Borders are in specified colors and styles and are within the box's margin. Padding is inside the border and is the same background color as the content.

./ ADD NAME=CH06LEV1SEC5.HTML

The workshop contains a Q&A section, quiz questions, and an exercise to help reinforce what you've learned in this hour. If you get stuck, the answers to the quiz can be found after the questions.

Q&A

[file:///C:/Documents%20and%20Settings/dani/Asztal/Sams%20Teach%20Yourself%20CSS%20in%2024%20Hours_2ndEd/0672329069/ch.htm#ch06qa1q1a1 Q.] What kind of element is a table cell? Is that block or inline?
> >
[file:///C:/Documents%20and%20Settings/dani/Asztal/Sams%20Teach%20Yourself%20CSS%20in%2024%20Hours_2ndEd/0672329069/ch.htm#ch06qa1q1 A.] It's neither inline nor block. The display value for a table cell () is special; it's table-cell. An element that has been set display: table-cell is displayed like a table cell (of course). This is a special type of block element, although there are some limitations; a table-cell element can't have a margin, for example. You'll learn more about tables and CSS in [file:///C:/Documents%20and%20Settings/dani/Asztal/Sams%20Teach%20Yourself%20CSS%20in%2024%20Hours_2ndEd/0672329069/ch17.html#ch17 Hour 17], "Styling Tables."
[file:///C:/Documents%20and%20Settings/dani/Asztal/Sams%20Teach%20Yourself%20CSS%20in%2024%20Hours_2ndEd/0672329069/ch.htm#ch06qa1q2a2 Q.] What is an em, anyway? Is it related to the size of a capital M?
[file:///C:/Documents%20and%20Settings/dani/Asztal/Sams%20Teach%20Yourself%20CSS%20in%2024%20Hours_2ndEd/0672329069/ch.htm#ch06qa1q2 A.] Not really, although that's where it gets the name from, historically. In CSS, an em is defined as a measure equal to the size of the font; it is a square that is as tall as the font size and as wide as it is tall. It's not related to letter M officially because some fontsnon-English fontsdon't have the letter M, and CSS needs to be able to function with all fonts around the world.
[file:///C:/Documents%20and%20Settings/dani/Asztal/Sams%20Teach%20Yourself%20CSS%20in%2024%20Hours_2ndEd/0672329069/ch.htm#ch06qa1q3a3 Q.] Okay, then what's a pixel? And a point? And how do percentages work?
[file:///C:/Documents%20and%20Settings/dani/Asztal/Sams%20Teach%20Yourself%20CSS%20in%2024%20Hours_2ndEd/0672329069/ch.htm#ch06qa1q3 A.] A pixel is basically one dot on a screen; if you've got 800x600 resolution displaying on your monitor, it is showing you 800 pixels across and 600 pixels down. A point is 1/72 of an inch in CSS. Percentages are based on the width of the containing block. You'll learn more about CSS's units of measurement in [file:///C:/Documents%20and%20Settings/dani/Asztal/Sams%20Teach%20Yourself%20CSS%20in%2024%20Hours_2ndEd/0672329069/ch09.html#ch09 Hour 9], "Fonts and Font Families," and [file:///C:/Documents%20and%20Settings/dani/Asztal/Sams%20Teach%20Yourself%20CSS%20in%2024%20Hours_2ndEd/0672329069/ch16.html#ch16 Hour 16].

Quiz

[file:///C:/Documents%20and%20Settings/dani/Asztal/Sams%20Teach%20Yourself%20CSS%20in%2024%20Hours_2ndEd/0672329069/ch.htm#ch06qa2q1a1 1.] Is the
element block or inline? How can you tell?
[file:///C:/Documents%20and%20Settings/dani/Asztal/Sams%20Teach%20Yourself%20CSS%20in%2024%20Hours_2ndEd/0672329069/ch.htm#ch06qa2q2a2 2.] What is the correct order of the box model, from outside to inside?
#
border, margin, padding, content
  1. padding, border, margin, content
  2. margin, border, padding, content
  3. margin, padding, border, content
[file:///C:/Documents%20and%20Settings/dani/Asztal/Sams%20Teach%20Yourself%20CSS%20in%2024%20Hours_2ndEd/0672329069/ch.htm#ch06qa2q3a3 3.] Consider the following style rules:
body { background-color: red;<br />color: white; }<br />h1 { color: black;<br />padding: 1.5em;<br />border: 5px solid green;<br />background-color: yellow;<br />margin: 0.5em; }<br />

What is the color of the margin around an

? What is the color of the padding?

Answers

[file:///C:/Documents%20and%20Settings/dani/Asztal/Sams%20Teach%20Yourself%20CSS%20in%2024%20Hours_2ndEd/0672329069/ch.htm#ch06qa2q1 1.] Because horizontal rules are on separate lines and don't occur inline,
must be block. You can check by looking it up in the HTML 4.01 specification on the W3C's website, http://www.w3.org/.
[file:///C:/Documents%20and%20Settings/dani/Asztal/Sams%20Teach%20Yourself%20CSS%20in%2024%20Hours_2ndEd/0672329069/ch.htm#ch06qa2q2 2.] (c). The outermost part of the box is the margin, then the border, and then the padding around the content.
[file:///C:/Documents%20and%20Settings/dani/Asztal/Sams%20Teach%20Yourself%20CSS%20in%2024%20Hours_2ndEd/0672329069/ch.htm#ch06qa2q3 3.] The color of the margin would be the background-color of the containing box; assuming the <body> contains the

, the color would be red. The background-color of the

determines the color of the padding, so the padding color is yellow.

Exercise

Reading about margins and padding is one thing, but actually using them is how you'll learn to master them. Create a web page with some blocks to style
or

work well for this, as do the

through

headingsand set various values of margin and padding on each.

Make sure that you know the difference between the margin and padding by setting the padding around a block to 1 em, then the margin. Add in a border and you'll be able to see even more clearly that padding is within the border line and margin is without.

./ ADD NAME=CH07.HTML