7 days of WordPress plugins, themes & templates - for free!* Unlimited asset downloads! Start 7-Day Free Trial
  1. Code
  2. HTML & CSS

Quick Tip: Flex Your Images

Scroll to top
Read Time: 2 mins

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.

Step 2: Add The CSS

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 ProductFinal ProductFinal Product

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

Did you find this post useful?
Want a weekly email summary?
Subscribe below and we’ll send you a weekly email summary of all new Code tutorials. Never miss out on learning about the next big thing.
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.