O'Reilly

background-size Matters

By on  

CSS background-size

It's something that makes all men live in fear, and are often uncertain of. It's never spoken, but the curiosity is always there. Nine out of ten women agree in the affirmative. Advertisers do their best to make us feel inadequate but tell us it can improve. Yes gentlemen...it appears that size matters.

background-size, that is. The background-size CSS property allows developers to designate the size at which a background-image should appear within an element. MooTools Developer Christoph Pojer employs the background-size technique on his website, allowing for his masthead to look "full" on browsers of all sizes, even mobile. Let's look at how to use the mystical background-size property.

background-size CSS

The background-size property has a few predefined values and then the usual numeric-based values:

  • contain: Ensures that the entire background-image will display by showing the image at a scaled size.
  • cover: Scales the background image so that the smallest dimension reaches the maximum width/height of the element.
  • length/percentage: Any custom numeric size

Believe it or not, the fun part is assigning the length and percentage sizes. Here are some examples of the different usages of background-size:

/* base header classes */
#header {
	/* header dimension! */
	height: 350px;
	
	/* additional background properties */
	background-repeat: no-repeat;
	background-position: center center;
	
	/* some box shadow for good fun */
	box-shadow: rgba(0,0,0,0.20) 0 10px 10px;
}

/* cover */
#header.flex {
	/* size matters */
	background-size: cover;
}

/* contain */
#header.flex {
	/* size matters */
	background-size: contain;
}

/* flex, fun */
#header.flex {
	/* size matters */
	background-size: 100% auto;
}

Christoph's website uses the last example, allowing for a great view of the JavaScript fanboy at all browser sizes. Check out my demos to see

The subtle awesomeness provided by using background-size is somewhat amazing. I'm usually quite skeptical of window size and resize effects but this technique helped me to see the value and ease in working with fixed dimensions and variable effects based on client browser size. background-size is supported in Firefox, Safari, Chrome, Opera, and IE9+.

What do you think about this technique -- neat trick or useful tool? Would you use this on your personal website? How about a business website?

Photos featured in this post were taken in London during the MooTools Hackathon.

Track.js Error Reporting

Recent Features

  • Page Visibility API

    One event that's always been lacking within the document is a signal for when the user is looking at a given tab, or another tab. When does the user switch off our site to look at something else? When do they come back?...

  • 9 Mind-Blowing Canvas Demos

    The <canvas> element has been a revelation for the visual experts among our ranks.  Canvas provides the means for incredible and efficient animations with the added bonus of no Flash; these developers can flash their awesome JavaScript skills instead.  Here are nine unbelievable canvas demos that...

Incredible Demos

  • Resize an Image Using Canvas, Drag and Drop and the File API

    Recently I was asked to create a user interface that allows someone to upload an image to a server (among other things) so that it could be used in the various web sites my company provides to its clients. Normally this would be an easy task—create a...

  • Record Text Selections Using MooTools or jQuery AJAX

    One technique I'm seeing more and more these days (CNNSI.com, for example) is AJAX recording of selected text. It makes sense -- if you detect users selecting the terms over and over again, you can probably assume your visitors are searching that term on Google,...

Discussion

  1. You are the God of CSS!
    Thanks for this post :)

  2. CSS3 I suppose?

    What I liked on Chris’ site is how the text boxes repacked as the page got narrower.

  3. Thanks for the great article. Not a lot out there that covers the background-size property. Nice to see it used in real situations.

  4. The noob

    Does not work for me on IE6 sp2, you are a liar. Shame on you.

    Thank you anyway.

    • The post says IE9!

    • Wayne

      Incredible, isn’t it? Seems like the noob didn’t read the post!

  5. This property is great but use it with caution, it can slow down the rendering considerably. I was wondering why my animation was so laggy and it turned out it was just this feature—if you think about it, the browser has to resize the image at every redraw (WebKit doesn’t seem to cache the resized image)

  6. Especially if you want create some background-patterns based on CSS3 you need the property background-size.

  7. dwfresh

    hi, so i didn’t see a difference between
    ‘background-size: 100% auto’ and ‘cover’ ??
    Is there a diffference ?
    thanks for the cool article.

  8. cashdollar

    what the hell is the difference between 100% auto and cover? It’s exactly the same in Chrome.

  9. I’m also trying to figure out the difference between 100% auto and cover?

    Great technique though. I’m using it at the new design of my site. Clearly it can be useful for both professional sites and personal.

    Thanks for the write up!

  10. Okay, so I discovered the difference between “100% auto” and “cover”. The “100% auto” value will simply set the size of the image to 100% of the parent element on the specified axis, and “cover” will make sure that the whole parent element is filled with the background image.

  11. Stan Rogers

    The difference between “100% auto;” and “cover” is that cover means “100% auto OR auto 100%, depending on which dimension you need to adjust, okay?;” (which is not a valid CSS value entry).

  12. I just stumbled across the Webkit performance issue too. Adding this to the element with the background image seems to really help performance.

    -webkit-transform: translate3d(0,0,0);

  13. I’d discover this technique early May, but it’s kinda useless if your client demands LTE IE8, plus if you use it in combination with transparent images, it doesn’t come out as nice as you might wish because of the scaling.

    I’d rather see a fix for LTE IE8, I was working on this but so far no cure found… If someone has come across a fix, please share :P

  14. Hi,

    This is a great overview of the background-size property.
    I’ve implemented a polyfill that implement “background-size: cover;” and “background-size: contain;” in IE8: https://github.com/louisremi/background-size-polyfill

    Give it a try!

  15. If you’re unsure stick to “cover” and not “100% auto” ::: cover does what it “says” it covers the screen ( forces ) Width & Height 100% not only Width 100% :::

  16. IE8-supporting fans of background-size: cover; rejoice!


    filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src='[image path]', sizingMethod='scale');

  17. Jordan

    Absolute Legend!!!! thank you soo much mate!

  18. Arild Orholm

    This is a great way of understanding the background-size tag, thanks a bunch. Ended up using a @media (max-width) { body-tag with cover to get some responsiveness from the site I am working on, works great!

  19. Jacob

    Hey, this is great!
    Question: Any idea how to dynamically remove a background image and replace with a color if the browser hits a minimum width? (ie: with Mobile devices?)

    • Google CSS Media queries: you run different CSS based on the pixel width of the device.

  20. Is there possibility to set background canvas size instead of image. When using sprite images, sometimes when content height goes higher than expected another image from the sprite is visible. So if we can set max canvas size that would be gold.
    Thanks.

  21. For those who question the difference between 100% auto and cover: try 50% or anything else but 100% and see the difference.

  22. Ash

    Also great for creating hi-res background images on retina screens i.e. create an image twice the size you wish to display and set the background-size to half the width of your image.

  23. Skweekah

    This isnt the first time David Walsh has gotten me out of a tough situation. Love your work make! Keep on keepin’ on!

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!

Recently on David Walsh Blog

  • OSCON Portland:  Conference  Discount!

    O'Reilly puts on the best web industry conferences in the world.  These conferences include Fluent Conference, Velocity Conference, and the upcoming OSCON in Portland, Oregon from July 20-24.  Open Source Convention (OSCON) is a conference that focuses specifically on open source developers and the tools and possibilities...

  • Follow Redirects with cURL

    I love playing around with cURL. There's something about loading websites via command line that makes me feel like some type of smug hacker, just like tweeting from command line does. I recently cURL'd the Google homepage and saw the following: I found it weird that Google...

  • Developers Have WordPress, Amateurs Have Squarespace, Professional Designers Have the NEW Webydo!

    Web design platforms have traditionally come in one of two varieties. There are the solutions like WordPress and Drupal that are incredibly powerful, but an understanding of web development and coding is required to be able to use those platforms effectively. On the other side of the...

  • Chris Coyierâs Favorite CodePen Demos II

    Hey everyone! Before we get started, I just want to say it’s damn hard to pick this few favorites on CodePen. Not because, as a co-founder of CodePen, I feel like a dad picking which kid he likes best (RUDE). But because there is just so...

  • GSAP + SVG For Power Users: Motion Along A Path

    Now that the GreenSock API is picking up steam, there are many tutorials and Getting Started guides out there to provide good introductions to the library, not to mention GreenSock’s own Forum and Documentation. This article isn’t intended for beginners, but rather a...