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.
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" />
There must not be a space between the number and px. In other words, use
130px, not 130 px.
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:
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:
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.
Happy coding!
Gnubee