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

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

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

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="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="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.

my dogmy dog 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 and vertically and then a fixed image.



Ready for more? Background images are next. Part D of Demo 3.

Go back to the Exercise 3 page.

© Claudia Faulk. Updated 1.17