Advertisement

Quick Tip: Flex Your Images

by
Student iconAre you a student? Get a yearly Tuts+ subscription for $45 →

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!

Advertisement