If you are learning CSS the Box Model is one of the first things you should learn and w3schools provides a perfect example. All HTML elements can be considered as boxes. In CSS, the term “box model” is used when talking about design and layout.
The CSS box model is essentially a box that wraps around HTML elements, and it consists of: margins, borders, padding, and the actual content.
The box model allows us to place a border around elements and space elements in relation to other elements.
The image below illustrates the box model:
Explanation of the different parts:
- Margin – Clears an area around the border. The margin does not have a background color, and it is completely transparent
- Border – A border that lies around the padding and content. The border is affected by the background color of the box
- Padding – Clears an area around the content. The padding is affected by the background color of the box
- Content – The content of the box, where text and images appear
In order to set the width and height of an element correctly in all browsers, you need to know how the box model works.
This will be our final result using only one image. (you can download exercise files at bottom)
How to do this? LET’S GO!
In simple terms: We are displaying only the left side of the image hiding the right half, then on rollover we are moving the image half way over to display the right side.
1. Create an image twice as wide as the size you’ll need. The left side of the image will be the non rolled over image and the right half will be the rollover part of the image.
2. Below is the HTML code used, make sure it has a class so our CSS code knows where to look. This will act as our CSS placeholder for the rollover image.
<a class=”imageRollover” href=”#”> </a>
3. Now for the CSS that will do the magic. Let’s get the image to look like we want when nothing is rolled over:
background: url(“rollover_image.jpg”) no-repeat; (This is the image to be used 260×108)
display: block; (this will display the entire image)
width: 130px; (display 130px wide, half the size of our image)
height: 108px; (display 108px high)
text-decoration: none; (This takes off the default styles used on links)
That will display the left half of our image. Now, we want to move our image 130px (half our image width) to the left to reveal the right side when rolled over.
background-position: -130px 0;
This moves our image 130 pixel to the left on :hover (note: background-position: Xposition Yposition)
That’s all there is to a single image rollover in CSS. ENJOY!