Bite Size Standards offers concise web development tutorials, tips, and tricks written by designers and developers who are passionate about web standards. More about us
In Part 1 of this article we explained that there are two techniques you can use to place an image within a block level element:
IMG element in the block level element, within the markup;The technique you choose depends on your needs. In this article we will focus on centering a background image using CSS.
We will use a 400x200 DIV and a 310x150 image as examples for this article. The DIV will have a 1px solid red border for clarifying purposes only.
This is the easiest and most flexible way to center an image, and is appropriate for presentational images that don't contain content. The markup contains only the DIV container for the image and we will use the CSS background property to position the image.
The following lines of code do the work:
div.back-image {
width:400px;
height:200px;
border:1px solid red;
background-image:url(path/bob.jpg);
background-repeat:no-repeat;
background-position:center center;
}
<div class="back-image"></div>
These lines of code will center the image within the DIV.
Finally, for the sake of simplicity, we can apply the shorthand declaration for our background property and rewrite our CSS like this:
div.back-image {
width:400px;
height:200px;
border:1px solid red;
background:url(path/bob.jpg) no-repeat center;
}
The CSS2.1 specs – Section 14.2.1 says:
~ CSS2.1 SpecificationIf only one percentage or length value is given, it sets the horizontal position only and the vertical position will be 50%.
That's why I've only added the center value for the background-position property.
Commenting is closed for this article.
Kilian Valkhof
: http://kilianvalkhof.com
6 January 2007, 23:03 : Permanent link to comment
I wasn’t aware that omitting one percentage value would center it both vertically and horizontally, nice bit(e) of knowledge there :)
web
: http://www.ericwebster.net
13 January 2007, 14:35 : Permanent link to comment
Interesting, what about accessibility? If this image is meant for content and not for design you could also put the image tag inside the back-image container, then with css hide it.
Because the image would be cached, this should not increase download time.
Shimon
: http://www.chossonandkallah.com
14 January 2007, 19:04 : Permanent link to comment
Is it semanticly right?
Su
: http://
15 January 2007, 01:42 : Permanent link to comment
<i>[...]and is appropriate for presentational images that don’t contain content.</i>
Web: What?
Shimon: Are you just asking, or implying it’s not? If it’s strictly a presentational image, then there aren’t really any semantics to be worried about, no?
David Levin
: http://www.angrysam.com
17 January 2007, 23:01 : Permanent link to comment
Nicely done. very clean.
Will the same CSS work if you use percentage width for the DIV (percent height is a whole new nightmare)?