HTML Post #4: Divs & Classes

Div Tags

A div tag is very similar to a paragraph tag. The difference from a rendering perspective is that paragraphs have a padding at the top and bottom by default. You can use div tags just like p tags.

Float Style

A div, and other tags, can have a float style. This can float the element on the left or the right. Here’s an example:

<div style="float: right">This floats on the right</div>
<div style="float: left">This floats on the left</div>
<div style="clear: both">This displays under the floats</div>
This floats on the right
This floats on the left
This displays under the floats

Yes, “clear: both” will clear all the floats above it. You can do “clear:left” to place is below the lowest left floating element. Float styles can be used with images as well.

CSS Classes

Styles can be declared once and referred using the class attribute. These styles can be declared using a stylesheet file or a style element. A stylesheet is better because it can be used by multiple pages by adding one line inside the html header:

<link rel="stylesheet" type="text/css" href="http://example.com/main.css" />

If you want to just play a little bit, you can put a style section in the html header:

<style type="text/css">
/* This is a style comment. */
/*

Put your stylesheet here in the html header!

*/
</style>

You can take this:

<div style="float: left; color: red;">Red Left</div>
<div style="float: left; color: red;">Red Left</div>
<div style="float: left; color: red;">Red Left</div>
<div style="float: left; color: red;">Red Left</div>

And turn it into this:

<style type="text/css">
.left-red { float: left; color: red; }
</style>
...
<div class="left-red">Red Left</div>
<div class="left-red">Red Left</div>
<div class="left-red">Red Left</div>
<div class="left-red">Red Left</div>

Note that the class in the style starts with a period and in the div doesn’t. This is because you are telling the browser that left-red is a class. If it started with a letter, the browser would think it was an element, like a “div” tag. Also, curly braces surround what would be in the style attribute.

Now, go play around for 30 minutes with some html. If you have a question, feel free to ask.