Positioning with CSS and a background image

CSS is oh so very useful with positioning background images throughout a Website.  You can specify where you want the image to appear within an element by specifying how many pixels up or down, left of right. 

So for example, to load an image in to a DIV, you could use the following CSS:

 

#mydiv {

background-image: url(pathtoyourimage.jpg);

}

 

Make sure you specify a height and width of the DIV.  By default the image will repeat throughout the DIV, to not have the css background repeat, use "no-repeat".

 

background-image:url(pathtoimage.jpg) no-repeat;

 

What if you need the CSS background image to be positioned differently? Use the following CSS!

 

background-position: 10px 20px;

 

The first parameter gives how many pixels from the left, the second parameter from the top.

CSS background positioning is also quite useful for buttons.  Say if you wanted to change an image when hovered over, background position can do this.  Create a button image. The image could have the identical next to each other, but one with a hover state.

  CSS background position example

Say if each button was 50px by 25px, would would specify this height and width in your CSS.  The image would be bigger than this because it has both images, but this doesn't matter, as the hover state will be hidden.  To integrate this in to your site, try the following.

 

#mybutton a {

width:50px;

height:25px;

background-image: url(mybutton.jpg) no-repeat;

background-position: 0px 0px;

}

 

Now, when you hover your mouse over, the following CSS will adjust the background, making the background position shift to only show the hover state, the normal state will be hidden, because we specified using CSS a height and width, so the rest of the image is hidden, so for your hover state, you could use the following:

 

#mybutton a:hover {

background-position:  0px -25px;

}

 

This would, for examples sake, move the example image above, upwards, only showing the hover state in the element.

 

Hope this has been a help.