Today's Question:  What does your personal desk look like?        GIVE A SHOUT

Put Your HTML in a Box

  Scott Allen        2011-08-19 08:22:58       3,828        0    

In the first article in this series, I walked through the basics of cascading style sheets (CSS) and showed how CSS can make your code easier to maintain. CSS allows you to keep your presentation rules separate from your content, and I showed you some of the benefits this separation provides. In this article, I’ll move forward with CSS and describe how to position elements on a page.

The first step in understanding how to position elements is to understand the fundamental model of CSS—the box model.

The Box Model

Every element you place on a page creates a box. You cannot always see the boundaries and the borders of the boxes you create, but the boxes are there. A div element creates a box, as do h1,img,span, and td elements. Each box has properties you can set with CSS. I’ve illustrated some of these properties in Figure 1.


Figure 1 Border, padding, and margin

The padding of a box is the distance between the content of the box and the box’s border, and themargin is the distance between a box and any adjacent element. In other words, padding adds space inside the border, while a margin adds space outside the border. In the following CSS, I set both the padding and the margin to a distance of 10 pixels. This is why you can see so much white space in Figure 1.

  1. div
  2. {
  3.     border: thin solid #FF0000;
  4.     padding: 10px;
  5.     margin: 10px;
  6. }

The border surrounding every element is not visible by default, but by using CSS I can change the color of an element’s border, as well as the thickness and line style the browser uses when drawing the border. What you see in Figure 1 is the result of a style rule telling the browser to draw a solid, thin, red line around the box that each div element creates.

To be exact, the border of a box has three properties: width, style, and color. You can set the width of the border by using a keyword (thick, thin, or medium) or a unit of measurement (like ems or pixels). The previous CSS listing sets all the border properties on a single line by using a shorthand notation, but you can also call out each property explicitly, as shown here:

  1. div
  2. {
  3.     border-width:  5px;
  4.     border-style: double;
  5.     border-color: red;
  6.     padding: 10px;
  7.     margin: 10px;
  8. }

It’s also possible to explicitly specify the border, margin, and padding settings for each of the four sides of a box:

  1. div
  2. {
  3.     border:solid;
  4.     
  5.     border-bottom-color: Black;
  6.     border-bottom-width:10px;    
  7.     
  8.     border-top-color:Red;
  9.     border-top-width:5px;
  10.     
  11.     padding-left: 10px;            
  12.     margin-right: 15px;
  13. }

Setting each side explicitly requires a lot of typing, but fortunately, you can use another shortcut notation here, too. If you include four units of measurement in a single style for border width, padding, or margin, the browser applies the measurements to the top, right, bottom, and left sides of the box, respectively. For example, in the following CSS, the right side of every div element will have a 10-pixel border, a 5-pixel padding, and a 2-pixel margin.

  1. div
  2. {
  3.     border:solid black;
  4.     border-width: 5px 10px 15px 5px;
  5.     padding: 10px 5px 3px 13px;
  6.     margin: 0px 2px 10px 0px;
  7. }

I hope that you can see why the box model is an important concept to master when you think about layout and positioning. The ability to tweak the margin and padding around individual pieces of content gives you fine-grained control over the location and appearance of your content.

As I discussed in the first article, most web browsers have a set of default styles, and these default styles can include default margin and padding settings. If you want to be sure that you start with a clean and consistent set of defaults, you can use a CSS Reset style sheet. The goal of a CSS Reset is to set the styles for all elements to a known state, and then you can override the styles with your own custom style sheet. On my blog (odetocode.com/blogs/scott/archive/2009/11/26/css-resets.aspx), I have included some links to popular CSS frameworks and reset style sheets.

If you want a simple and effective reset for padding and margins, you can use the following rule at the beginning of a style sheet. This rule tells the browser to set the margin and padding to zero for all elements.

  1. *  
  2. {
  3.    margin:0px; 
  4.    padding:0px; 
  5. }

I haven’t told you everything you need to know about the box model just yet. In the context of positioning and layout there are some subtle behaviors you need to know.

When Margins Collapse

One important behavior I want to emphasize is how vertical margins collapse. Imagine that you have twodiv elements appearing one right after the other on a page:

  1. <div>
  2.     This is the first div. 
  3. </div>
  4. <div>
  5.     This is the second div.
  6. </div>

Then, in a style sheet, you use the following rule to apply margins to all divelements.

  1. div
  2. {    
  3.     margin-top: 50px;
  4.     margin-bottom: 20px;
  5. }

It’s tempting to think that you’ll have a total distance of 70 pixels between the two consecutive divelements (a 20-pixel margin for the bottom of the first div, plus a 50-pixel margin for the top of the second div). However, the distance will only be 50 pixels. When vertical margins are adjacent, the CSS specification says that the margins must collapse into a single margin, and the width of the single margin will be the maximum of adjoining margin widths.

Remember, I’m talking about adjoining vertical margins: horizontal margins never collapse. In addition, in some special cases vertical margins do not collapse. For example, margins do not collapse in the case of floating or absolutely positioned elements, which you’ll see examples of later.

Boxes, Blocks, and Breadth

Another aspect of the box you can control is the width. It’s important to note that you can only set the horizontal width of block elements. Block elements are elements that display on a new line by default, likep, div, li, and tr. These are different from inline elements like span, a, and strong. Inline elements do not force their content onto a new line.

As an example, consider the following markup:

  1. <div class="content">
  2.   <h1>Welcome!</h1>
  3.   <p>
  4.         I'd like to welcome everyone
  5.         to my simple demonstration. 
  6.   </p>
  7. </div>
  8. <p>
  9.     This is some footer content 
  10.     for the bottom of the page. 
  11. </p>

I’m going to apply the following styles to the markup:

  1. .content
  2. {    
  3.     width: 200px;
  4.     padding: 10px;
  5.     background: #CCCCCC;
  6. }
  7.  
  8. h1
  9. {
  10.     background: #CCCC99;
  11.     border-bottom: solid thick black;
  12.     text-align:center;
  13. }

The markup and styles combine to give you the display in Figure 2.


Figure 2 Using the width property

Notice that constraining the width of the content div also constrains the h1 and p elements inside the div. In the case of the h1 element, I’ve centered its text content inside the constrained box. The footer content at the bottom is outside the constrained div and can stretch farther horizontally. You’ll find many pages with a columnar design using an approach similar to this one. Specifically, to create a column of content you wrap all the content inside a div element and set the width of the div.

Also notice how the 10-pixel padding keeps the content from touching the outer edges of the box. The outer edges are where the background color stops. Let’s use a 10 pixel margin instead of a 10 pixel padding.

  1. .content
  2. {    
  3.     width: 200px;
  4.     margin: 10px;
  5.     background: #CCCCCC;
  6. }

The updated style gives us the display shown in Figure 3.


Figure 3 Using margin instead of padding

Padding and margin settings are subtle, but they can make obvious changes to the aesthetics of a page. You should know that the padding, margin, and border sizes together add up to the total width of a box. In other words, the total width of the constrained div is actually 220 pixels. I specified 200 pixels for the content and then added 10 pixels of padding (which we changed to be margin) to the left and right sides. Understanding how to calculate the total width is important in some scenarios, like when you are trying to align the width of an element with the width of an image on the page.

Floating Boxes

Although a single-column layout is effective for some pages, having two or more columns appear side by side is a popular design. This doesn’t happen naturally. As I mentioned previously, a block element like a div always wants to appear on a new line. Thus, in the normal flow of a page, block elements appear one after the other in a downward direction. If you want columns to appear side by side, you need to use the float property.

Floating is common with images. For example, look at the following markup:

  1. <img src="DSC00546.JPG" alt="peonies" />
  2. <div class="description">
  3.     A beautiful specimen. 
  4. </div>

With the normal flow of elements, the text of the div appears on a new line, as shown in Figure 4.


Figure 4 Normal flow

The following is a style that tells the image to float on the left. The style gives me the display shown in Figure 5.

  1. img
  2. {
  3.     float:left;
  4.     margin: 10px;
  5. }


Figure 5 Floating left

When you float a block element, you tell the browser to shift the element to the left (or to the right) as far as it can, and to break the normal flow of elements. Any block element following the float will flow as though the float did not exist. Thus, the text in Figure 5 is allowed to appear to the right of the image. If I had even more text, it would look like Figure 6.


Figure 6 Text flowing around image

Something magical happens if I also tell the text to float and set its width property, as you can see in Figure 7.


Figure 7 Columns made with floats

Figure 7 is the result of the following style rules:

  1. img
  2. {
  3.     float:left;
  4.     margin: 10px;
  5. }
  6.  
  7. .description 
  8. {
  9.     float:left;
  10.     width: 300px;
  11. }

The float and the width properties stop the browser from wrapping the text around the image. A general rule of thumb is always to set the width of a floated element (an image has a width defined implicitly). You can use this technique to horizontally stack as many block elements as you like, but there has to be enough horizontal space. If someone reduces the width of the browser window when looking at the content in Figure 7, the floated description will shift downward and appear below the image.

Closely related to the float property is the clear property. I’m going to use the following markup as an example:

  1. <img src="DSC00546.JPG" alt="flowers" />
  2. <div class="description">
  3.     A beautiful specimen.
  4. </div>
  5. <p id="footer">
  6.     Page footer....
  7. </p>

I want the footer paragraph to appear at the bottom of the page, but because the boxes above the footer are floating, and because there is enough room, the footer moves itself up and to the right of the image. (See Figure 8.) If the browser window is wide enough to accommodate the footer, it would move itself to the right of the description text (because the description text is also floating).


Figure 8 Undesirable wrapping

To solve this problem you can set the clear property of the footer.

  1. #footer
  2. {
  3.     clear:both;
  4. }

An element with the clear property set to the value “both” will not move up beside a float. You can also set the clear property to “left” or “right,” and then the element will not move up beside an element floated to the left or right, respectively (but it will move beside an element floated in the opposite direction).

Using floats and clearing floats entails some subtleties, and I encourage you to use the basics I’ve given you and experiment with them yourself. For now, I want to move on to the position property.

In Position

No article about positioning would be complete without looking at the position property itself. The position property and the float property are similar in that the browser uses both of them to calculate the position of a box on the screen. However, the float property always takes a box out of the normal flow and allows other content to flow beside it, while the position property tells the browser to make one of several calculations depending on the value of the position property: static, absolute, fixed, or relative.

Static positioning is the default. Elements using static positioning exhibit the behavior you’ve seen so far. Each element appears one after the other in sequential order.

Relative positioning allows you to offset an element with respect to its default position. You can specify the relative position by using the top, left, bottom, and right properties. Typically, relative positioning is specified by using only the top and left properties, as shown here:

  1. .content
  2. {    
  3.     position: relative;
  4.     top: 20px;
  5.     left: 30px;
  6.     margin: 10px;
  7.     background: #CCCCCC;
  8. }

Each of the top, left, bottom, and right properties specify how far away the browser will offset an element from the respective edge. For instance, in the last style rule, the browser will move the element 20 pixels down (away from the top) and 30 pixels to the right (away from the left). Negative values are also valid for these properties (to move an element up and to the left).

You have to be careful with relative positioning. Although an offset element remains in the normal flow, the browser would position the element that follows it as though the offset element was never relatively positioned. In other words, a relatively positioned element appears to everyone else as though it is in its static position. Relative positioning can create overlaps in content. (See Figure 9.) Unless the overlap is an effect you want to achieve, you need to be sure that relatively positioned content has enough space to display cleanly.


Figure 9 Undesirable overlap

Absolute positioning takes an element out of the normal flow; thus, an element with an absolute position has no effect on the position of any siblings that follow it. The top, right, bottom, and left properties specify the offset from the element’s containing box, which is typically the body of the HTML page. Also, the margins of an absolutely positioned element never collapse. The following CSS changes Figure 9 to Figure 10.

  1. .content
  2. {    
  3.     position: absolute;
  4.     top: 20px;
  5.     left: 30px;
  6.     margin: 10px;
  7.     background: #CCCCCC;
  8. }


Figure 10 Absolute positioning

Fixed positioning is similar to absolute positioning, but the browser positions the element relative to the browser window itself. This means that you can keep an element in a specific spot regardless of how big the page is and where the user scrolls.

Before I let you go, I want you to know that you can use percentage values when specifying width, top,right, bottom, and left properties. Percentages are useful when you want to position and size an element relative to the size of the display or surrounding content. The downside to using percentage values is that you won’t know just how many pixels the browser will use.

Conclusion

Now that you’ve reached the end of this article, let me tell you that positioning is one of the most challenging tasks you can undertake with CSS. The difficulties with positioning are partly due to the wide variety of web-capable devices. Not only will users view your pages in desktop browsers, but they’ll also visit your application using small netbooks, cell phones, gaming consoles, screen readers, and televisions. Making your site look its best all the time is hard when you’re presented with the different constraints and resolutions of all these devices. Apply what you’ve learned in this article with an iterative approach: design, test, tweak, and repeat.


Source : http://msdn.microsoft.com/en-us/scriptjunkie/ff805052.aspx

HTML  BOX  DIV  CONTAINER  FORMAT 

Share on Facebook  Share on Twitter  Share on Weibo  Share on Reddit 

  RELATED


  0 COMMENT


No comment for this article.