Try Tuts+ Premium, Get Cash Back!
Flex Your Images

Quick Tip: Flex Your Images

Tutorial Details
  • Difficulty: Beginner
  • Completion Time: 10 Minutes

One glaring reason why many developers have chosen fixed-width over elastic sites is because using inline images can destroy the layout of a site – much like a stampede of cattle that repeatedly kick you in the groin. It just isn’t fun at all. Sure, you can specify their widths using percentages or ems, but those methods aren’t ideal. In such instances, why not try using the background technique?

Step 1: Set Up The HTML

First, let’s create a very simple html file.

<div id="container">
    <div id="image">
    </div>
    <p>
        Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Vestibulum ullamcorper
        magna quis velit. Nam vitae dui et massa convallis vulputate. Aliquam ante magna,
        fermentum nec, scelerisque eget, semper quis, ipsum. Fusce consectetuer enim quis
        lorem. Morbi elit turpis, consequat ac, lacinia nec, dignissim ac, velit. Proin
        mauris orci, rutrum a, suscipit eu, sagittis et, nisi. Quisque at mi ac magna fermentum
        elementum.
    </p>
</div>

Step 2: Add The CSS

#container
{
    width: 50%;
    margin: auto;
    padding: 1em;
    background: #3d332a;
    color: #b8ada2;  
}

#image
{
    height: 300px;
    background: url(Girl.jpg) no-repeat center;
}

In order for our container div to be flexible, I’ve set the width to be 50% of the browser window. Next, I’ve set the margins to auto in order to center the contents. The padding, background, and color are simply aesthetic styling.

The div tag with an id of “image” is where we’ll add the background image. The key here is that I’m not setting a specific width to the image – only the height. When you add the image as a background, you’ll want to make sure that you “center” it (no-repeat center). This, in effect, will force the main focus of your image to be displayed at all times. *Note – Make sure that you use an image that has the main focal point in the middle.

You’re Done

View your work in a browser and try increasing and decreasing the browser window. There are a few things to keep in mind when using this method.

  • Make sure that you use images that are as wide as they’ll ever need to be.
  • The center of your image should be the focal point.
  • Center the background image.
  • Consider making the maximum width of your container div equal to the full width of the image.
  • Additionally, consider adding a minimum width to make sure that your image doesn’t shrink too much.
Final Product

Have a great weekend. Let’s meet back here Monday! By the way, be sure to follow us on TWITTER!

Tags: tips
Note: Want to add some source code? Type <pre><code> before it and </code></pre> after it. Find out more
  • http://cyberantix.org Connor

    This weekend Quick Tip’s a neat idea! By the way, nice quick tip ;-).

  • Coucchy

    Great tip! Good tutotial, keep them coming please.

  • http://www.darkhousemedia.com Adam Jackett

    I think this site needs more quick tips like this. It may not be super helpful to everyone but not everyone thinks of alternative methods of doing things.

  • http://www.ragard-jp.com/en/ ne-design

    Great Tip!
    Never thought of using background to make it flex.

  • http://www.nettuts.com Editor

    @Adam – I agree! This is something that I’m planning on doing every weekend. The way I see it, by Saturday, we all have “code overload syndrome”. It might be nice to have some quick tips that don’t fry your brain.

  • http://www.picbi.com ali

    these sort of articles are worth much more than the long ones we get,

    well done

  • http://www.webholics.de Mario

    I would use this technique only for layout images not for photos or graphics which are relevant to the content. It is not accessible. Without CSS you won’t see the image and without the alt-attribute the image would be invisible for a text reader.

  • rene

    At first I thought it was something about Adobe Flex.

  • http://www.ben-griffiths.com Ben Griffiths

    Really nice really simple and really effective, thanks :D

  • http://mdnet.imeem.com MD

    Great post! thnx :)

  • http://www.brothersgrimmstudios.com Daniel Erickson

    If you want it to be accessible, just put a copy of the image inside of it and use “display: none;” in the stylesheet. That way when css is turned off, the photo will be viewable.

  • http://chaosfyregraphix.exofire.net SniperFox

    “much like a stampede of cattle that repeatedly kick you in the groin.”

    Wow. That’s…..a pretty nice analogy actually.

    I might have to try this out. I’ve been wanting to get into fluid layouts, but this was one thing that was messing me up [Images that just get in the way, and look terrible when the resolution is shrunk.]

  • http://www.annecampbelldesign.com Anne

    Great tip! I have fixed-width-itis and will definitely try this. I agree with many of the above commenters – I tend to glaze over at the long tutorials, but I love quick tips like these. Thanks!

  • http://www.prestigebulletin.com Jonathan

    This is a great trick. And Daniel good call on the “display: none;” will try it out when I play around with this tip over the weekend ;-)

  • http://jaredrhizor.com/ Jared Rhizor

    Neat idea. Of course this wouldn’t work with all photos, but useful for many.
    It would be better with a constant amount of space on all sides of the photo. If your screen is big enough, there are huge ugly gaps.

  • http://www.configuracionvisual.com dlv

    “It may not be super helpful to everyone but not everyone thinks of alternative methods of doing things.”
    i agree with Adam Jackett.

  • http://ha.xors.org Braden Keith

    Very lovely tip

  • http://inspirationup.com Joefrey Mahusay

    Great tips. more tutorial on mootools and wordpress please.

  • Zach LeBar

    cool idea. maybe they’ll be adopted by the other ‘TUT sites.

  • http://www.mabucplus.com Mark Abucayon

    Simple but very clean, I like it and also give us more tuts love this website.

  • http://www.detacheddesigns.com Jeffrey Way
    Author

    The key here is to remember that this is simply another tool for your bag. It won’t be appropriate in all circumstances. However, in reference to the usability comments – I would agree that adding the image into the code and then setting the display to “none” would be a good way to go.

    Another thing to consider is…what do you do when the images are being populated from a database? For this situation, it could be argued that inline styling is acceptable in such a case…as much as I hate to say it. That way, you can dynamically set the background in the code.

    What do you all think?

  • http://ondadiluce.com Mauro

    This is great! thanks :)

  • http://www.freshclickmedia.com Shane

    @Jeffrey – as much as inline styling is frowned upon, there are times when it is more appropriate. As you say, it’d be better to set the images using inline styling, rather than have perhaps hundreds of unique IDs. Semantically, it’d be very difficult to give each a meaningful ID too, so inline styling in this case would be better I think.

    I’ve never used this technique before, but have seen it mentioned in a web design book – can’t remember which one. Is it this one – http://www.transcendingcss.com/ ?

    Thanks for posting.

  • http://www.freshclickmedia.com Shane

    [sorry for the repeat comment]

    The technique works great for images that have their main interest in their centre (as you mention), but isn’t useful for other types of image (though perhaps you could fix this with CSS for images with left/right focal points).

    @Jeffrey (perhaps the focal point of the image could be stored in the database and the CSS styling applied appropriately. Though that’s probably over the top.)

  • http://jameslao.com James Lao

    I don’t agree with this tip for several reasons:

    1. You need inline styling to do this unless you are willing to edit a CSS file every time you post a new image.

    2. It isn’t semantic at all. An image that is content and not a design element should not be a background. And now you have an empty div.

    3. This is terrible SEO, which ties back to #2. Search engines will not spider the image.

    I’ve seen this done with the max-width CSS property and some Javascript which may be a better solution.

  • http://www.insicdesigns.info insic

    for those who disagree… dont read the post. submit your own tutorial and lets see how good are you. :)

  • http://www.brandoneley.com Brandon Eley

    I commented soon after this article was published and it seems to have been deleted, even though I actually changed the CSS so it was both semantic and better for SEO.

    My original comment below (see if we can actually get it published this time…):

    With respect to the tutorial author, this teaches bad coding practices and has two major flaws:

    * The blank DIV tag gives no information to visitors with images turned off, screen readers, etc. It’s a big accessibility issue.

    * The image shown as a CSS background can’t have ALT tags, can’t be linked, etc. The lack of ALT tags is both an accessibility and SEO issue.

    It’s very easy to accomplish the same thing with being a little more creative with your CSS:

    http://brandoneley.com/imagedemo/demo.html

    Using the CSS overflow property you can get effectively the same effect without compromising your accessibility or SEO.

    It works in IE 6/7, Safari and Firefox.

    • jmarreros

      I agree with you, your example is great, thanks.

  • Ty

    Very sweet and simple idea, a best Web Standards Secret Modus Operandi

  • http://www.crysfel.com crysfel

    this technique is awesome ;)

  • http://talkingtofu2.iblogger.org Taylor Satula

    +++ Good, thanks many helpful

  • http://www.littledeer.ie Oisin

    Brandon’s method in the comments is I think a more elegant solution.

    However for those who want to go the background-image way and still provide alternative text content for screen readers and search engines you could place text in the div and set text-indent:-9999px in the CSS.

  • shod4n

    Wow, perfect solution!

  • http://mbavio.com.ar Martin Bavio

    ????

    Dude, have you ever heard of semantics?

    I like this site, but I think you have to be more careful about what are you teaching…

  • http://www.detacheddesigns.com Jeffrey Way
    Author

    @Martin – Yes, I have heard of semantics. This is simply an alternative approach if needed. And I should inform you that this method was originally created by Andy Clarke.

  • http://www.abccomunicacion.com Lex

    I’m working on a better AND semantic methos, 100% CSS. If i can make it work in all A-grade browsers, i will post it here.

  • http://mbavio.com.ar Martin Bavio

    @Jeffrey,

    So what if Andy Clarke created it? It´s wrong anyway!

    That “gurues have always the true word” is a conception that I dont really follow, they can know more and have more experience, but that isnt the same as having always the true.

    And I dont discuss the method itself, I think it´s cool, but I also think you need to add the problems that it has with semantics, and why semantics are good, otherwise, let´s go back to tables and empty gifs!

    Cheers.

  • anonymous coward

    demo does not validate

  • Pingback: Flexible Width Images for Elastic Layouts | MikeWhoBikes

  • http://www.kickandy.com Gatot

    It’s ok tutorial trik html.

    thank u

  • http://www.riverside.hr Kevin

    Great tip and great trick!

    It inspired (as I can see by the comments) some people to come up with their own ideas and solutions for the same problem. I think that the original method is good for background images, but may not be the best solution for the in-page ones; for the latter, there are some neat methods in comments.

    Tip’s interesting, out of box, it makes people think, and inspires; that’s the real value of it.

    Thank you and keep up the good work/tips!

  • Ryan Kelly

    Yes, using max-width would allow you to keep the image in the page and keep the content and style separate.

    just set
    selector {
    max-width: 50em;
    }

    or whatever you want the container size to be. I’m pretty sure this will center the image, but if it doesn’t just add some more properties.