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

A Smarter Way To Learn HTML & CSS(2015)

22
Div

You can break up a webpage into sections, called divs. Each of these divs can have its own styling, using either a class or an id. Coders commonly create separate divs for headers, navigation bars, main content, and footers. Here’s some code that creates a div for the main content of the page. Since there would be only one such section, I use an id rather than a class.

div#main {
font-size: 1.1em;
margin: .1em .2em .2em .2em;
}

Here’s the HTML that assigns the id.

<div id="main">
<h2>Here’s the whole story.</h2>
<p>It’s soft.</p>
<p>It’s fluffy.</p>
</div>

All elements within this div will be contained in a section that has a margin on each side. Unless you’ve written overriding CSS code that changes the font-size of certain text elements, all elements in the div, which are children of the div, will be 110% of “normal” size (however you’ve defined “normal” when you styled the body). If those individual text elements are styled smaller (less than 1em) or larger (more than 1em) than normal, they’ll be scaled up or down in relation to the 1.1em specified for the div, not the “normal” specified for the body. So if you specified 1em (the browser’s default size) for the body, 1.1em for the div, and 1.5em for h3 headings, the headings will be 150% of 110% of the browser’s default text size.

Note that the <div> tag is closed, and that the elements that are enclosed by the <div> tags are indented 2 spaces, since they’re all children of the div.

When you’re styling a div that appears only once on the page, like the navigation section, main content, or footer, it’s best to create an id rather than a class for it. If there’s a possibility a div style may be used more than once, define a class. For example:

div.special {
margin: .1em .5em .1em .5em;
}

Any div assigned the “special” class will have extra margins on the left and right. The result is that it will be inset.

Add a div id to your CSS file. Give it 3em left and right margins. Assign it the font family Arial, Helvetica, sans-serif. In your HTML file code a div with that id. Inside the div code a heading and paragraph. Save the files and display the page.

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

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

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