HTML Cookbook Basic HTML Course

It's Easy!


Alternate Version

CSS Dimensions

We have used dimensions in our lessons without talking about them very much. This lesson will focus on how to use dimensions in CSS.

The dimension properties are height and width. They can be used with pixels or with percent. We will use the dimension properties to set the size of divs and images.


HTML vs. CSS

In HTML, we use height and width as image attributes.

<img src="../images/mallrat.jpg"
width="155" height="130"
alt="mallrat" />

In CSS we replace the height and width attributes with the height and width properties.

<img src="../images/mallrat.jpg"
style="width:155px; height:130px"
alt="mallrat" />

mallrat

There must not be a space between the number and px. In other words, use
130px, not 130 px.


Div Dimensions

We can also set the dimensions of a div.

<div style="width: 310px; height: 260px">
content
</div>


Let's put an image in a sized div. I'll also use background-color to show the div dimensions.

<div style="width: 310px;
height: 260px;
background-color: #ccccff">
<img src="../images/mallrat.jpg"
style="width:155px; height:130px"
alt="mallrat" />
</div>

Appears as:

mallrat

Now that we have the concept of a sized image in a sized div, we could add a background image to div to use as a "canvas".

<div style="width: 310px;
height: 260px;
background-color: #ccccff;
background-image: url(../bg/water.gif)">
<img src="../images/mallrat.jpg"
style="width:155px; height:130px"
alt="mallrat" />
</div>

Appears as:

mallrat


Our styling might be easier if we make a class in an internal stylesheet:

<style type="text/css">
<!--
div.bg {
width: 310px;
height: 260px;
background-color: #ccccff;
background-image: url(../bg/water.gif)
}
-->
</style>


Now our code above looks like:

<div class="bg">
<img src="../images/mallrat.jpg"
style="width:155px; height:130px"
alt="mallrat" />
</div>

A class or id could also be added to the stylesheet for the image dimensions.



Assignment

  1. Make a page that has an image in a div. Use background-color and/or background-image to show that the div is larger than the image.

  2. Preparation for coming lessons: Find 1 or 2 images to use as a background image in a div. They may be "textures" (wood, water, stone) or a "scenes" (landscape, seascape). Find 2 images to be place on top of a background image.

Happy coding!
Gnubee

Links
Tips
Tools
References
Rules
HTML Help Gnubee - Newsgroup
HTML Course Contents (Home)

Valid XHTML 1.0!

Valid CSS!