Update: The simpler technique at the end.
While designing my new site I decided to make the layout completely liquid. That always means more work. But I wanted it to be wider than 800px, and at same time it should fit a 800×600 screen. Finally the whole site was liquid and I ran into problems. It simply doesn’t look good when your images stop at half of the total column width, because they should not be too big for lower resolutions. I had to find something that made the images as wide as the column.
If you just put an image in a liquid column, that image defines some kind of min-width and destroys all your work, ’cause if you don’t pay attention, your images runs into other columns.
The solution is pretty simple. You don’t need an <img>
. What you need is background
. I made a <p>
tag and put some describing text in it. The paragraph gets its background via CSS. But don’t put the properties into your global CSS file. Don’t waste that space. Put them directly in the tag. Yeah, that’s still valid.
<p style="background: url(nice-image.jpg);">You see a nice image.</p>
So, now we got a background. Cool. You don’t see it, because text is in front of it? Let’s fix this.
First, we want the <p>
to be as wide as the surrounding <div>
, or anything else. That’s not the problem. width: 100%
will do the work. We’ll do the same with the height. Percents won’t work now, so use the height of your image (My image is 100px high). To prevent some unneeded effects, we put also a no-repeat
in the style definition. After all, we got this:
<p style="background: url(nice-image.jpg) no-repeat; width: 100%; height: 100px;">You see a nice image.</p>
The text is still in front of your background which was supposed to be an as-wide-as-the-column-image? We simply push the text under the bottom. Here comes the trick: padding-top: 100px; height: 0;
. So forget the height: 100px
, padding-top
takes over. Finally something important: Hide the overflow and set font-size to 1px.
Here is how the final code looks like:
<p style="
background: url(nice-image.jpg) no-repeat;
width: 100%;
height: 0px;
font-size: 1px;
padding-top: 100px;
overflow: hidden;
">You see a nice image.</p>
Replace the URL and padding-top according to your needs. You can see it in action at the home page of my website. If everything is all right, it should even work with IE.
The advantages of this technique are:
- Fits liquid columns
- Prevents non-CSS browsers from even loading the image
- Offers a description when images is not shown
- Suitable for every image in the desired column
- Extremely cool
Update:
Put the image in a p
and style the paragraph with overflow: hidden;
. Same effect.