Lesson 9

Working with Margins, Padding, Alignment, and Floating

What You’ll Learn in This Lesson:

  • Image How to add margins around elements

  • Image How to add padding within elements

  • Image How to keep everything aligned

  • Image How to use the float property

Now that you’ve learned some of the basics of creating web content, in this lesson you’ll learn the nitty-gritty of using CSS to enhance the display of that content. In the lessons that follow, you’ll dive in to using CSS to control aspects of your entire web page rather than just individual pieces of text or graphics.

Before you tackle page layout, however, it is important to understand four particular CSS properties individually before putting them all together:

  • Image margin and padding—For adding space around elements

  • Image align and float—For placing your elements in relationship to others

The examples provided in this lesson are not the most stylish examples of web content ever created, but they are not intended to be. Instead, the examples clearly show just how HTML5 and CSS are working together. Although this lesson is short in terms of page count, the concepts deserve careful reading and hands-on practice. When you master CSS through this and other sections of the course, as well as through ongoing practice of what you’ve learned, you’ll be able to use your own design skills to enhance what can be (and often is) the relatively basic underlying scaffolding.

Using Margins

Style sheet margins enable you to add empty space around the outside of the rectangular area for an element on a web page. It is important to remember that the margin property works with space outside the element.

Following are the style properties for setting margins:

  • Image margin-top—Sets the top margin

  • Image margin-right—Sets the right margin

  • Image margin-bottom—Sets the bottom margin

  • Image margin-left—Sets the left margin

  • Image margin—Sets the top, right, bottom, and left margins as a single property

You can specify margins by using any of the individual margin properties or by using the margin property. Margins can be specified as auto, meaning that the browser sets the margins in specific lengths (pixels, points, or ems, among others) or in percentages. If you decide to set a margin as a percentage, keep in mind that the percentage is calculated based on the size of the containing element. So, if you set the margin-left property of an element within the body to 25%, the left margin of the element will end up being 25% of the width of the entire page. However, if you set the margin-left property of an element within that element to 25%, it will be 25% of whatever that original 25% was calculated to be.

The code in Listing 9.1 produces four rectangles on the page, each 250 pixels wide and 100 pixels high, with a 5-pixel solid black border (see Figure 9.1). Each rectangle—or <div>, in this case—has a different background color. If you want the margin around each <div> to be 15 pixels on all sides, you can use the following:

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

Note

You can remember the shorthand order in at least two different ways. First, if you think of an element as being a rectangle, start at the top and work your way clockwise around the sides: top side, right side, bottom side, left side. Or you can use a first-letter mnemonic device and remember TRBL (pronounced “trouble” or “tribble,” if you’re a Star Trek fan), which also represents a possible state of being in case you forget the order of the margin properties.

Also note that the TRBL order is valid for padding properties and border properties as well.

You can also write that in shorthand, using the margin property:

margin: 15px 15px 15px 15px;

When you use the margin property (or padding or border) and you want all four values to be the same, you can simplify this even further and use the following:

margin: 15px;

When using shorthand for setting margins, padding, or borders, three approaches apply, which vary based on how many values you use when setting the property:

  • Image One value—The size of all the margins

  • Image Two values—The size of the top/bottom margins and the left/right margins (in that order)

  • Image Three values—The size of the top margin, the left and right margins (they are given the same value), and the bottom margin (in that order)

  • Image Four values—The size of the top, right, bottom, and left margins (in that order)

You might find it easiest to consistently use one value or consistently use all four values, but that’s certainly not a requirement.

Listing 9.1 Simple Code to Produce Four Colored <div> Elements with Borders and Margins

<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>Color Blocks</title>
    <style>
       div {
          width: 250px;
          height: 100px;
          border: 5px solid #000000;
          color: black;
          font-weight: bold;
          text-align: center;
       }
       div#d1 {
          background-color: red;
          margin: 15px;
       }
       div#d2 {
          background-color: green;
          margin: 15px;
       }
       div#d3 {
          background-color: blue;
          margin: 15px;
       }
       div#d4 {
          background-color: yellow;
          margin: 15px;
       }
    </style>
  </head>
  <body>
    <div id="d1">DIV #1</div>
    <div id="d2">DIV #2</div>
    <div id="d3">DIV #3</div>
    <div id="d4">DIV #4</div>
  </body>
</html>

You can see the output of Listing 9.1 in Figure 9.1.

An output screen titled ‘Color Blocks’ shows four rectangular blocks, one below the other, with equally thick borders. The blocks are labeled from D I V number 1 to D I V number 4 and are shaded red, green, blue, and yellow, respectively.
Figure 9.1 The basic color blocks sample page shows four color blocks, each with equal margins.

Next, working with just the margin property in the style sheet entries in Listing 9.1, let’s shift the margins. In this example, you can’t really see the right-side margin on any of these <div> elements because there’s nothing to the right of them, and they’re not aligned to the right. With that in mind, you can set margin-right to 0px in all of these. Beyond that, the next set of goals is to produce the following:

  • Image No margin around the first color block

  • Image A left-side margin of 15 pixels, a top margin of 5 pixels, and no bottom margin around the second color block

  • Image A left-side margin of 75 pixels and no top margin or bottom margin around the third color block

  • Image A left-side margin of 250 pixels and a top margin of 25 pixels around the fourth color block

This seems as though it would be straightforward—no margin is being set around the first block. But if there is a margin at the top of the second block, there really will be a visible margin between the first and second blocks, even if you do not specify a margin for the first block.

The new style sheet entries for the four named <div> elements now look like this:

div#d1 {
  background-color: red;
  margin: 0px;
}
div#d2 {
  background-color: green;
  margin: 5px 0px 0px 15px;
}
div#d3 {
  background-color: blue;
  margin: 0px 0px 0px 75px;
}
div#d4 {
  background-color: yellow;
  margin: 25px 0px 0px 250px;
}

The result of the code changes (see Figure 9.2) seems random but is actually quite useful for pointing out a few other important points. For example, recall that one of the goals was to produce no margin around the first color block, and you might expect the border of the color block to be flush with the browser window. But as Figure 9.2 shows, there is a clear space between the content of the page and the frame of the browser window.

A screenshot of the color blocks displayed with variations in their margins.
Figure 9.2 Modifications to the color blocks sample page display some different margins.

If you were working on element placement—which we get to in the next lesson—this would cause a problem in the layout. To ensure that your placements and margins are counted from a position flush with the browser, you need to address the margin of the <body> element itself. In this case, you add the following to your style sheet:

body {
  margin: 0px;
}

Another “gotcha” to remember is that if you have two bordered elements stacked on top of each other but no margin between them, the point at which they touch appears to have a double border. You might therefore consider making the top element’s border-bottom half the width and then also make the bottom element’s border-top half the width. If you do this, the borders appear to be the same width as the other sides when the elements are stacked on top of each other.

In addition, you might think that using a left-side margin of 250 pixels—the width of the <div> elements—would begin the fourth color block where the third color block ended. That is not the case, however, because the third color block has a margin-left of 75 pixels. For those elements to be even close to lining up, the margin-left value for the fourth div would have to be 325 pixels.

Changing the styles to those shown in the following code produces the spacing shown in Figure 9.3:

body {
  margin: 0px;
}
div {
  width: 250px;
  height: 100px;
  color: black;
  font-weight: bold;
  text-align: center;
}
div#d1 {
  border: 5px solid #000000;
  background-color: red;
  margin: 0px;
}
div#d2 {
  border-width: 6px 6px 3px 6px;
  border-style: solid;
  border-color: #000000;
  background-color: green;
  margin: 10px 0px 0px 15px;
}
div#d3 {
  border-width: 3px 6px 6px 6px;
  border-style: solid;
  border-color: #000000;
  background-color: blue;
  margin: 0px 0px 0px 15px;
}
div#d4 {
  border: 5px solid #000000;
  background-color: yellow;
  margin: 0px 0px 0px 265px;
}

These changes give the <body> element a zero margin, thus ensuring that a margin-left value of 25 pixels truly is 25 pixels from the edge of the browser frame. It also shows the second and third color blocks stacked on top of each other, but with modifications to the border element so that a double border does not appear. In addition, the fourth color block begins where the third color block ends.

A screenshot of the color blocks displayed with a closer relationship to each other.
Figure 9.3 A third modification to the color blocks pulls items into closer relationship with each other.

As you can see in Figure 9.3, some overlap occurs between the right edge of the third color block and the left edge of the fourth color block. Why is that the case, if the color blocks are 250 pixels wide, the third color block has a margin-left value of 15 pixels, and the fourth color block is supposed to have a 265-pixel margin to its left? Well, it does have that 265-pixel margin, but that margin size is not enough because you also have to factor in the 6 pixels of border. Changing the margin property for the fourth color block to reflect the following code makes the third and fourth blocks line up according to plan (see Figure 9.4):

margin:0px 0px 0px 276px;

A screenshot of the color blocks displayed with the margin changed to allow 11 pixels for the border width.
Figure 9.4 Changing the margin to allow for 11 pixels of border width.

As shown in these examples, margin specifications are incredibly useful for element placement, but you must use caution when setting these specifications.

Padding Elements

Adding padding is similar to using margins, in that both add extra space to elements. The big difference is where that space is located. Recall that margins are added to the outsides of elements. On the other hand, padding adds space inside the rectangular area of an element. Because the padding of an element appears within the element’s content area, it assumes the same style as the content of the element, including the background color.

Caution

Most designers assume that if you create an element with a width of 50 pixels and a height of 30 pixels and then set the padding to 5 pixels, the remaining content area will be 40 pixels by 20 pixels. But this is not the default action in most web browsers or the HTML/CSS specifications. Instead, the width of the content area will be 50 pixels, but the entire box will take up 60 pixels in width (50 + 5 for the left padding + 5 for the right padding). If there are any borders defined, they are added to the total rendered width as well. The height acts the same way. In Lesson 10, “Understanding the CSS Box Model and Positioning,” you will learn how to deal with this and make boxes behave as you expect.

You specify the padding of a style rule by using one of the padding properties, which work much like the margin properties. The following properties are available for use in setting the padding of style rules:

  • Image padding-top—Sets the top padding

  • Image padding-right—Sets the right padding

  • Image padding-bottom—Sets the bottom padding

  • Image padding-left—Sets the left padding

  • Image padding—Sets the top, right, bottom, and left padding as a single property

As with margins, you can set the padding of style rules by using individual padding properties or the padding property. You can also express padding by using either a unit of measurement or a percentage.

Following is an example of how you might set the left and right padding for a style rule so that there are 10 pixels of padding on each side of an element’s content:

padding-left: 10px;
padding-right: 10px;

As with margins, you can set all the padding for an element with a single property (the padding property). To set the padding property, you can use the same three approaches available for the margin property. Following is an example of how you would set the vertical padding (top/bottom) to 12 pixels and the horizontal padding (left/right) to 8 pixels in a style rule:

padding: 12px 8px;

Following is more explicit code that performs the same task by specifying all four padding values:

padding: 12px 8px 12px 8px;

In all the figures so far in this lesson, note that the text DIV #1, DIV #2, and so on appears at the top of the colored block, with just a little space between the border and the text. That amount of space hasn’t been specified by any padding value, but it appears as a sort of default within the element. Listing 9.2 shows some examples of the specific control you can have over your element padding. All the color blocks are 250 pixels wide and 100 pixels high, have a 5-pixel solid black border, and have 25 pixels of margin (see Figure 9.5). The fun stuff happens within the padding values for each individual <div>.

Listing 9.2 Simple Code to Produce Four Colored <div> Elements with Borders, Margins, and Padding

<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>Color Blocks</title>
    <style>
      body {
         margin: 0px;
      }
      div {
         width: 250px;
         height: 100px;
         border: 5px solid #000000;
         color: black;
         font-weight: bold;
         margin: 25px;
      }
      div#d1 {
         background-color: red;
         text-align: center;
         padding: 15px;
      }
      div#d2 {
         background-color: green;
         text-align: right;
         padding: 25px 50px 6px 6px;
      }
      div#d3 {
         background-color: blue;
         text-align: left;
         padding: 6px 6px 6px 50px;
      }
      div#d4 {
         background-color: yellow;
         text-align: center;
         padding: 50px;
      }
    </style>
  </head>
  <body>
    <div id="d1">DIV #1</div>
    <div id="d2">DIV #2</div>
    <div id="d3">DIV #3</div>
    <div id="d4">DIV #4</div>
  </body>
</html>

A screenshot of the color blocks displayed with the variable padding.
Figure 9.5 The basic color blocks sample page shows four color blocks with variable padding.

You should immediately recognize that something is amiss in this example. The color blocks are all supposed to be 250 pixels wide and 100 pixels high. The color blocks in Figure 9.5 are not uniform because the width and height declarations apply only to the content box. Any padding or border lengths are added to those dimensions in the final rendered display.

If you place the text in a <p> element and give that element a white background (see Figure 9.6), you can see where the padding is in relationship to the text. You will learn about this effect in detail in Lesson 10, as well as how to fix it.

A screenshot of the color blocks displayed with the variable padding with respect to the text within each block.
Figure 9.6 Showing the padding in relationship to the text.

The greatest number of tweaks or nudges you make in your web design with CSS will have to do with margins and padding. Just remember: Margins are outside the element; padding is inside it.

Keeping Everything Aligned

Because content on a web page doesn’t always fill the entire width of the rectangular area in which it is displayed, it is often helpful to control the alignment of the content. Even if text within a rectangular area extends to multiple lines, alignment enters the picture because you might want the text left-justified, right-justified, or centered. Two style properties enable you to control the alignment of elements inside a box: text-align and vertical-align.

You saw examples of these style properties in action (when aligning images) in Lesson 8, “Working with Colors, Images, and Multimedia,” but it doesn’t hurt to mention these properties again here because alignment plays a role in overall page design as well.

As a refresher, using text-align aligns an element horizontally within its bounding area, and it can be set to left, right, center, or justify.

The vertical-align property is similar to text-align except that it is used to align elements vertically. The vertical-align property specifies how an element is aligned with its parent or, in some cases, the current line of elements on the page. “Current line” refers to the vertical placement of elements that appear within the same parent element—in other words, inline elements. If several inline elements appear on the same line, you can set their vertical alignments the same to align them vertically. A good example is a row of images that appear one after the next; the vertical-align property enables you to align them vertically.

Following are common values for use with the vertical-align property:

  • Image top—Aligns the top of an element with the current line

  • Image middle—Aligns the middle of an element with the middle of its parent

  • Image bottom—Aligns the bottom of an element with the current line

  • Image text-top—Aligns the top of an element with the top of its parent

  • Image baseline—Aligns the baseline of an element with the baseline of its parent

  • Image text-bottom—Aligns the bottom of an element with the bottom of its parent

Alignment works in conjunction with margins, padding, and (as you’ll learn shortly) the float property to enable you to maintain control over your design.

Centering Blocks of Content

One thing you may have noticed when you were working in the previous section is that centering, especially centering blocks of content, can be challenging. While you can center text and other inline elements (such as links or buttons) with text-align: center; getting things like images or text boxes to center is difficult. Many novice web designers fall back on the old and very outdated <center> tag. But please: Don’t use the <center> tag.

As we just mentioned, it’s old and outdated; it’s also been deprecated, which means it’s been removed from the HTML specification. Browser makers can support it (and other deprecated syntax) if they wish, but they don’t have to, and in the future, it may stop working completely. But more importantly, the <center> tag does only one thing: It defines the presentation of the contents as centered. It doesn’t provide any semantic meaning or otherwise affect the structure of the document. Instead of using the <center> tag, you should use CSS.

If you’re trying to center an image or a block of content in your design, the easiest way is to change the horizontal (left and right) margins to auto, like so:

margin-left: auto;
margin-right: auto;

You can also use the margin shorthand property:

margin: 0 auto;

This works only on elements that have a width set that is smaller than the current container. If you try to center a <div> that does not have the width set, nothing will happen. But if you add a width or maximum width value and then the margin: 0 auto; style, the browser will automatically add space on the left and right to center it. You will learn other ways to center block elements in Lesson 12, “Creating Layouts Using Modern CSS Techniques.”

Understanding the float Property

The float property is an important tool for understanding a popular type of CSS-based layout and design. Briefly stated, the float property allows elements to be moved around in the design so that other elements can wrap around them. You often find float used in conjunction with images (as you saw in Lesson 8), but you can—and many designers do—float all sorts of elements in the layout.

Elements float horizontally, not vertically, so you have to concern yourself with just two possible values: right and left. An element that floats will float as far right or as far left (depending on the value of float) as the containing element will allow it. For example, if you have three <div> elements with float set to left, they will all line up to the left of the containing body element. If you have these <div> elements within another <div>, they will line up to the left of that element, even if that element itself is floated to the right.

You can best understand floating by seeing a few examples, so take a look at Listing 9.3. This listing simply defines three rectangular <div> elements and floats them next to each other (floating to the left).

Listing 9.3 Using float to Place <div> Elements

<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>Color Blocks</title>
    <style>
      body {
         margin:0px;
      }
      div {
         width: 250px;
         height: 100px;
         border: 5px solid #000000;
         color: black;
         font-weight: bold;
         margin: 25px;
      }
      div#d1 {
         background-color: red;
         float: left;
      }
      div#d2 {
         background-color: green;
         float: left;
      }
      div#d3 {
         background-color: blue;
         float: left;
      }
    </style>
  </head>

  <body>
    <div id="d1">DIV #1</div>
    <div id="d2">DIV #2</div>
    <div id="d3">DIV #3</div>
  </body>
</html>

Figure 9.7 shows the resulting page. Already you can see a problem: These three color blocks were supposed to be floated next to each other. Well, actually they are floated next to each other, but the browser window is not wide enough to display these three 250-pixel-wide blocks with 25 pixels of margin between them. Because they are floating, the third one simply floats to the next line.

An output screen titled ‘Color Blocks’ shows three equally sized rectangular blocks, labeled from D I V number 1 to D I V number 3 and are shaded red, green, blue, positioned at the top-left, top-right, and bottom-left, respectively.
Figure 9.7 Using float to place the color blocks.

You can imagine that this could be a problem in a specifically designed visual layout, so pay attention to your margins, padding, alignment, and floating while also testing within a target browser window size. Granted, the browser window in Figure 9.7 is a small one to make this point about floating elements moving to the next line when there is no room for them to fit where they should. In other words, if you open the same HTML file with a larger browser window, you might not see the issue; this is why you should always check your sites at different resolutions to see whether a fix is needed. The fix here is to adjust the margins and other size-related properties of your <div> elements.

Figure 9.8 shows another interesting possibility when the float property is used. This figure shows what happens with just a few changes to the code from Listing 9.3: making the color blocks only 100 pixels wide, reducing the margins to 10px, and changing the float alignment of the second color block to right (instead of left).

An output screen titled ‘Color Blocks’ shows three squares, labeled D I V numbers 1, 3, and 2 are shaded red, blue, and green positioned one after the other, horizontally. 1 and 3 are left aligned; 2 is right aligned.
Figure 9.8 Using float to place the color blocks.

However, something interesting has happened. The second color block now appears visually as the third color block because it is flush right. The second color block has a float value of right, so it has floated all the way to the right. The first and third color blocks are floating as far to the left as possible, regardless of the way in which the <div> code appears in the HTML, which is as follows:

<div id="d1">DIV #1</div>
<div id="d2">DIV #2</div>
<div id="d3">DIV #3</div>

Getting used to floating takes a lot of practice, especially when your page has additional elements rather than just a few colored blocks. For example, what happens when you add a basic paragraph to the mix? All elements placed after the floating element then float around that element. To avoid that problem, use the clear property.

The clear property has five possible values: left, right, both, none, and inherit. The most common values are left, right, and both. Specifying clear:left; ensures that no other floating elements are allowed to the left, clear:right; ensures that no other floating elements are allowed to the right, and so on. Using floating and clearing is a learn-by-doing process, so look for more situations in the Workshop at the end of this lesson.

Summary

This lesson introduced you to some of the most fundamental style properties in CSS-based design: margin, padding, and float. You learned how the margin property controls space around the outside of elements and how the padding property works with space within the elements.

After getting a refresher on the text-align and vertical-align properties you learned about in a previous lesson, you learned about the float property. The float property allows for specific placement of elements and additional content around those elements.

Q&A

Q. The examples of margins and padding in this lesson all had to do with boxes and text. Can I apply margins and padding to images as well?

A. Yes, you can apply margins and padding to any block-level element, such as a <p>, a <div>, an <img>, and lists such as <ul> and <ol>, as well as list items (<li>)—just to name a few. You can also apply margins and padding to inline elements, but the results may not be as you expect, so always test your pages in multiple browsers.

Q. Is there a good rule of thumb for when you should use margins versus padding?

A. You need to understand two differences between CSS margins and padding. The first difference is that padding on a link can be clicked or tapped to interact with it, while a margin cannot. Because of this, you should use padding, rather than margins, around links to make them easier to click.

There is also another difference you should be aware of. For block-level elements, the vertical margins will collapse together into a single margin that is equal to the largest individual margin. You saw this in this lesson. In Listing 9.1, each of the <div> elements had a top and bottom margin of 15 pixels, but the vertical space between the elements was not 30 pixels; it was just 15 pixels. If you change one of the elements to have a bottom or top margin of 20 pixels, the space between the elements will grow only 5 pixels. Vertical padding, because it is inside the element, does not collapse. Because vertical padding does not collapse, you should use the padding property whenever you want a set amount of space around the element, regardless of where it displays on the page. Otherwise, you should use margins.

Workshop

The Workshop contains quiz questions and exercises to help you solidify your understanding of the material covered.

Quiz

1. To place two <div> elements next to each other, but with a 30-pixel margin between them, what entry or entries can you use in the style sheet?

2. Which CSS style property and value are used to ensure that content does not appear to the left of a floating element?

3. What style sheet entry is used to place text within a <div> to appear 12 pixels from the top of the element?

4. What is the shorthand property to set the vertical margins to 1rem and the horizontal margins to 2rem?

5. Where is the padding applied to an element?

6. What non-shorthand properties would you use to set the padding of an element to 1 pixel from the top, 2 pixels from the right, and 6 pixels from the left?

7. What property would you use to align text to the vertical middle of the line?

8. What does the text-align: justify; property do?

9. How can you position a 50% wide paragraph to line up on the right side of the screen (with the text aligned to the left)?

10. Where would the text YOU ARE HERE display in the following HTML in a 640 × 480 screen?

<!doctype html>
<html lang="en">
  <head>
    <metacharset="utf-8">
    <title>Where does the text go?</title>
    <style>
      div {
        width: 100px;
        height: 100px;
        border: solid red 2px;
      }
      p {
        width: 300px;
        text-align: center;
      }
     .left { float: left; }
     .right { float: right; }
    </style>
  </head>
  <body>
    <div class="left"></div>
    <div class="right"></div>
    <p>YOU ARE HERE</p>
  </body>
</html>

Note

Just a reminder for those of you reading these words in the print or e-book edition of this book: If you go to www.informit.com/register and register this book (using ISBN 9780672338083), you can receive free access to an online Web Edition that not only contains the complete text of this book but also features an interactive version of this quiz.

Answers

1. You can use several entries. The first <div> uses the style property margin-right:15px. The second <div> uses the style property margin-left:15px. Or you can assign the full 30 pixels to either <div> by using margin-right or margin-left, as appropriate. In addition, at least the first <div> needs to have float:left assigned to it.

2. In this instance, use clear:left.

3. You would use padding-top:12px.

4. You would use margin: 1rem 2rem;.

5. The padding is applied inside the element.

6. You would use padding-top: 1px;, padding-right: 2px;, and padding-left: 6px;.

7. You would use vertical-align: middle;.

8. It lines up the text so that it is straight on both the right and left edges, with no rag.

9. You would use p { float: right; }.

10. The text would appear between the two boxes but closer to the left one.

Exercises

  • Image Fully understanding margins, padding, alignment, and floating takes practice. Using your own color blocks code or <div> elements, practice all manner and sorts of spacing and floating before moving on to the next lesson. The next lesson discusses the CSS box model as a whole, which encompasses the individual items discussed in this lesson.

  • Image While you’re at it, practice applying margins and padding to every block-level element you’ve learned so far. Get used to putting images within blocks of text and putting margins around the images so that the text does not run right up to the edge of the graphic.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
34.229.50.161