Cascading Style Sheets: Margins and padding

  1. A simple web page
  2. CSS
  3. Basic CSS syntax

For our first trick, we’ll add a nice margin on the left and right so that our text is not flush left and crowded. Use a text editor to create a style sheet called “reviews.css” in the same folder as your new web page. In that style sheet, add the following CSS:

body {

width: 80%;

margin-left: 10%;

text-align: justify;

}

This makes the web page 80% of the browser’s width, and makes a left margin of 10% of the browser width. Then, it fully justifies all text on the page.

When we specify widths and heights of blocks in percentages, we are specifying a percentage of the containing item. In this case, the body is contained by the html tag, which is the browser itself. If we had a paragraph inside of a table, and we specified that the table was 50% width and the paragraph was 50% width, the paragraph will be 50% the width of the table, which will be 25% of the width of whatever contains the table.

image 3

Now, I think that looks quite a bit better already, but that left margin is kind of empty. Let’s add a border to our left margin:

body {

width: 80%;

margin-left: 10%;

text-align: justify;

border-left-style: dashed;

border-left-color: orange;

border-left-width: .2em;

}

This adds a dashed orange border directly to the left of the text. The border is “.2em” in width, which is to say, 20% of the upper-case font size. The border will thus change in width proportionally to any changes in font size that the reader requires.

image 4

Our border is much too close to our text. It’s the same problem that we had when our text was flush left to the side of the browser. We can move the border further away from the text that it belongs to using padding. Add one more line to your CSS:

body {

width: 80%;

margin-left: 10%;

text-align: justify;

border-left-style: dashed;

border-left-color: orange;

border-left-width: .2em;

padding-left: 1em;

}

This adds a padding between the border and the text of one “em” width.

image 5
  1. A simple web page
  2. CSS
  3. Basic CSS syntax