CSS tricks, continued:
Floating photos in divs


The new projector is great --

Use View:PageSource from your browser's main menu to look at the CSS and HTML source code of this page. The photo in a box on the left is an HTML "div" styled as a CSS "class." I've named the class "photocap-l" because it is meant to contain a photo and caption, positioned as a unit to the left of some text.

It's simple enough to "float" an image to one side of a paragraph, but getting the caption to go along with it requires some packaging: a "div" to contain them both.)

I made the style rule for the div a class, not an id, so that I could use it again elsewhere on my site with different images and captions.

Reminder: CSS allows you to restyle any HTML tag, or to create your own "class" and "id" tags. Id tags are marked with a "#" in the CSS, and are used only once on a page; classes are marked with a period and can be used many times.


-- but I have to hide my eyes

If this page were a catalog of men's hats or a list of website reviews, I could line-up their pictures on the left and style all of their boxes the same way, starting each one with <div class="photocap-l">. Each box would float to the left of whatever paragraph I typed after it.

However, a column of boxes, all the same size and color, might look boring. So I also copied the CSS and modified it slightly to make another class called "photocap-r" -- which floats to the right and has a different background color. Now I could alternate paragaphs with pictures on the left and right.

Each version of the photocap div has these characteristics:

Make a copy of this page and try editing it to test different settings in the CSS, or different positionings of the divs within the HTML. For a simpler example of floating, see image-right float at w3schools. To do more complex things with the "float" attribute, see that site's full float tutorial. If you float a series of objects on one page, you will have to learn about "clearing" the floats to get text to line up normally again. See this float-confusion example.

For more on centering, floating and positioning page contents, see w3schools' Horizontal Align tutorial.

Next: Use more CSS and the "float-a-div" idea to create a menu for your pages.

Back to Bob's page on CSS centering