<< .. Go to : : Schedule : : Exercise 4 : : Demo 4A : : Demo 4B : : Demo 4C : : Demo 4D : : Demo 4E : : Demo 4F : : All Class Demos .. >>

Exercise 4 Demo: Part C : Using CSS to Align Images

This is the HTML and CSS you will need for Part C of Exercise 4.

Using CSS and Class Selectors to Align images

In Exercise Two we used tags as our selectors so we could style those tags on our html page. You can also create your own "class" to make a selector and then add it to tags as an attribute. We will create a couple of classes and add them to the image tag to determine where we want it to align on the page.

A class selector always has a period before its name. This tells the browser that it is a class and that its styles can be added to multiple tags as an attribute. We will create two classes, one named .leftside and one called .rightside .

<html>
<head>
<title>
Adding a Background Image </title>

<style type="text/css">

.leftside {float: left;

      margin-top: 2px;

      margin-right: 15px;

      margin-bottom: 2px;

      margin-left: 5px;

      }

.rightside {float: right;

      margin: 2px 10px 2px 10px;

      }

</style>
</head>

<body>

In the leftside selector I wrote out the margins separately. But in the rightside selector I used shorthand. The values go clockwise, starting with the top, then right, bottom, and ending on left. Just put a space between each value. Be sure to use the colon after the property and a semi-colon after the value.

When you use the class in the html you do not use the period. This is what the code would look like.

<img src="images/stellasm.jpg" class="leftside" alt="my dog">

my dog And there she is, my Stella dog, floating left, with a mragin around her. Image alignment with CSS. Works out pretty well and since it is a class, I can attach it to multiple images.

my dogNow we will try her with the right alignment. See if she moves to the right side of the page. And she did. Good dog Stella.

Here is the code I used:

<img src="images/stellasm.jpg" class="rightside" alt="my dog">

You can modify the amounts of margin you use. And use the class on mulitple images. We could try a couple more for fun.

bananas are good to eatbananas are good to eat Lots of bananas to fill out the page.

To really have an exciting webpage - sometimes you want to have an image in the background. We will try that next in several different ways.

Tiling to fill a whole page.
Tiling horizontally
Tiling vertically
A single fixed or scrolling image


For more about using Links go to Part D of Demo 4.

Go back to the Exercise 4 page.

© Claudia Faulk. Updated 9.17