Margins- A Smarter Way To Learn HTML & CSS (2015)

A Smarter Way To Learn HTML & CSS(2015)

16
Margins

You can put margins around paragraphs, headings, and many other HTML elements. A margin creates extra whitespace around the top, bottom, or sides of an element. For example, if you have a paragraph that would normally look like this…

Slow lorises are a group of several species of strepsirrhine primates which make up the genus Nycticebus. They have a round head, narrow snout, large eyes, and a variety of distinctive coloration patterns that are species-dependent.

…adding a left margin would add whitespace on the left, like this…

Slow lorises are a group of several species of strepsirrhine primates which make up the genus Nycticebus. They have a round head, narrow snout, large eyes, and a variety of distinctive coloration patterns that are species-dependent.

And adding a right margin, in addition to a left margin, would add whitespace on the right, like this…

Slow lorises are a group of several species of strepsirrhine primates which make up the genus Nycticebus. They have a round head, narrow snout, large eyes, and a variety of distinctive coloration patterns that are species-dependent.

If you wanted, you could specify top and/or bottom margins to add whitespace above and/or below the paragraph.

Here’s some CSS code that creates a class of paragraphs that I’ve named offset that adds margin space all around the text. The amount of whitespace is two times the size of default text.

p.offset {
margin: 2em 2em 2em 2em;
}

A more concise way to code equal margins on all four sides…

p.offset {
margin: 2em;
}

When you’re specifying all four margins in one statement, you specify them in clockwise order, starting at the top. Let’s say you want a right margin twice the size of default text, a left margin 1.75 the size of the font, and no margins on the top or bottom. You’d write…

p.offset {
margin: 0 2em 0 1.75em;
}

Note that when you want no margin, you write 0, not 0em.

If you want to add space between paragraphs, instead of or in addition to a first-line indent, specify a bottom margin. This code adds space between paragraphs.

p {
margin: 0 0 1em 0;
}

Instead of specifying all four margins, you can specify individual margins. An alternative to the example above is…

p {
margin-bottom: 1em;
}

You can also specify margin-top, margin-right, and margin-left.

Add a class of paragraphs to your CSS file that has extra whitespace all around it. Then add a paragraph to your HTML document that’s in this class. Display the page.

Sample CSS code is at:
http://asmarterwaytolearn.com/htmlcss/practice-16-1.html.

Sample HTML code is at:
http://asmarterwaytolearn.com/htmlcss/practice-16-2.html.

Find the interactive coding exercises for this chapter at:
http://www.ASmarterWayToLearn.com/htmlcss/16.html