Quick Tip: Fluid Width Images

I’ve been working on a mobile website which requires me to make the site practical and functional across a myriad of devices and their corresponding screen sizes. Usually, this isn’t much of a problem if it’s just text and background colors, because you can just leave the “width” attribute off of your element to have the text & colors fill the screen.

However, for this particular project, it requires the use of large, high quality images to be used as background images. This presents a problem the “background” CSS attribute will not expand or contract based on screen size; instead, it will go by the image size, taking up as much space as the image dimensions. The workaround is the following:

Add this line to your CSS: img { max-width: 100% }
In your HTML, add the image inside the containing div, making sure to NOT specify width and height in the img tag.
In the CSS, add “position:absolute” to that image. In the containing div’s CSS, add “position:relative”
It might also be beneficial to add “top:0″ and “left:0″ to the image CSS, to place it in the top left of the containing div.
What this does is two-fold. It allows you to place an image as the background of a div AND allows it to expand or contract in size based on the screen size. Heres the full code:

HTML

<div id="container">
<img src="images/bg.jpg" alt="" />
</div>

CSS

img { max-width:100% }

#container { position:relative }

#container img {
position:absolute;
top:0; left:0;
}

Two important things to remember when using this:

You’ve got to make the image as large as the biggest “version” of your site. So if the maximum width of your site is 1000px and you want the image to expand across all of it, the image must be 1000px.
Therefore, if you have a 1000px image, but are displaying the site on a smartphone, it’s still going to download that 1000px image; so be careful of image size. Make sure to optimize as much as possible.
I found the max-width technique from Ethan Marcotte’s books and articles, like this one. Let me know in the comments if this helps or you have any better solutions!

Our Office

Office Hours:
Monday thru Friday
8:30am to 5:30pm EST

Address:
1301 North Summit
Toledo, Ohio 43604 USA

Phone:
(419) 243-7445

Let's talk.

Have an idea or project you'd like to discuss? Contact us by filling out the form below for your digital, web, and software solutions!

Contact Us

To help us further reduce spam