CSS Stretch Background Image?

Q: Ever wonder that css can stretch a background image? So no matter what the monitor size the background image always stretches to meet the requirements?

A: There is no way to stretch or control the size of a background image using css. However, you could use the background, background-attachment and background-repeat porperties to achieve an alternative result…

Watch browser support for these though!

Well, CSS1 and CSS2 still can’t do the magic yet, but CSS3 can! Here’s how:-

The ‘background-size’ property

Is ‘background-stretch’ a better name?

Specifies the size of the background images. The section “Layering multiple background images” defines to which image of the ‘background-image’ property each of the comma-separated values applies.

If a comma-separated value has only one part (not counting the keyword ’round’), the second part is set to ‘auto’. Of the two parts, the first one refers to the width, the second to the height of the corresponding background image. The addition of the keyword ’round’ indicates that the width and height are approximate, as explained below. ’round’ on its own is equivalent to ‘auto auto round’.

The size of an image is established in two steps. The first step derives sizes as follows:

auto
The size that keeps the background image’s original aspect ratio. Additionally, if the other part of the value is also ‘auto’, the image has its intrinsic size.
<length>
A specific size.
<percentage>
The percentage is relative to the width or height of the area given by ‘background-origin’.

Negative values are not allowed. A size of zero is allowed, but causes the image not to be displayed. (The effect is the same as if it had been a transparent image.)

If the given size is accompanied by the keyword ’round’, and the computed value of ‘background-repeat’ is repeat for the horizontal and/or vertical direction, there is a second step: The UA must reduce the width, resp., height so that the image fits a whole number of times in the background area. In the case of the width:

If X ≠ 0 is the width of the image (i.e., the specified length or percentage, or the intrinsic width if the ‘background-size’ is ‘auto’) and W is the width of the background area, then the rounded width X’ = W / ceil(W / X)

The height is analogous. ceil() is a function that returns its argument if it is a whole number, otherwise the next bigger whole number.

If the width is reduced because of this formula, the aspect ratio is not retained, not even if the height was specifed as ‘auto’ and the vertical repeat as ‘no-repeat’. Ditto if the height is reduced.

Should ’round’ be specified for width and height separately? It then becoems possible to round in one direction and keep the aspect ratio in the other. E.g., instead of allowing the keyword in ‘background-size’, it could be one of the possible values in ‘background-repeat’: [ repeat | space | no-repeat | round ]{1,2}.

Is ’round’ the right word? How about ‘~’ in front of the number, or ‘approx’ or ‘about’?

Is it better allow the size of the image to be rounded up as well as down?

Here are some examples. The first example stretches the background image independently in both directions to completely cover the content area:

div {    background-image: url(plasma.png);background-size: 100%;background-origin: content}

The second example stretches the image so that exactly two copies fit horizontally. The aspect ratio is preserved:

p {    background-image: url(tubes.png);background-size: 50% auto;background-origin: border}

This example forces the background image to be 15 by 15 pixels:

para {    background-size: 15px;background-image: url(tile.png)}

This example uses the image’s intrinsic size. Note that this is the only possible behavior in CSS level 1 and 2.

body {    background-size: auto;background-image: url(flower.png)}

The following example rounds the height of the image to 25%, down from the specified value of 30%. At 30%, three images would fit entirely and a fourth only partially. After rounding, four images fit. The width of the image is 20% of the background area width and is not rounded.

p {    background-image: url(chain.png);background-repeat: repeat-y;background-size: 20% 30% round; }
About these ads

Posted on September 29, 2006, in General, Web Dev. Bookmark the permalink. 35 Comments.

  1. This works in firefox, not sure about IE :P

  2. This works in firefox, not sure about IE :P

  3. One more try…

    <body>
    <div style=" position:absolute;z-index:0;top:0;left:0;width:100%;height:100%; " >
    <img src="background.jpg" width="100%" height="100%">
    </div>
    <div style=" z-index:1;position:absolute; ">
    <!-- Page Content -->
    </div>
    </body>

  4. it’s easy to use css to stretch a background image to a specific size. just use the following :

    html:

    css:
    #background {
    position:absolute;
    display:block;
    z-index:0;
    left:0px; right:0px;
    top:0px; bottom:0px;
    width:100%; height:100%;
    }
    #bg {
    position:absolute;
    z-index:0;
    left:0px; top:0px;
    width:100%;
    height:100%;
    }
    .img1 { background-image:url(yourimage.jpg); }

    and that’s all. whatever size you specify inside #bg for width and height (min/max works too!) will be the background image’s exact size, so it never actually repeats!. The only tricky part is the #background container div. The settings it must have depend on what it is a child of. But, for the #bg child element to size the background image correctly, #background must have display:block;. Padding limitations, and margin limitations, ALSO work on this background stretching method. Have fun!

  5. WHOOPS, sorry about that response. the HTML got bleeped out. So if you don’t want to hit view page and dig for it, here it is again…

    div id=”background”
    div id=”bg” class=”img1″
    /div
    /div

    This works with any kind of image of course, stretches the background-image to any size or shape, works in all major browsers, and is very AJAX friendly.

  6. Armand from Latvia

    Tested the above method, but with no luck (in FF 2.0.0.9.)!

    http://armands.freehostia.com/nami/temp2.html

    I also don`t get why it should work.
    Because of display:block?

  7. Work in Firefox and IE!

    HTML:

    text

    CSS:
    body {
    margin: 0px;
    padding: 0px;
    overflow: hidden;
    }

    #back {
    position: absolute;
    height: 100%;
    width: 100%;
    }

    #content {
    overflow: auto;
    position: relative;
    height: 100%;
    width: 100%;
    left: 0px;
    top: 0px;
    }

  8. Problems with posting html code

    HTML:

    div id=”back”
    img src=”back.jpg” width=”100%” height=”100%”
    /div

    div id=”content”
    text here
    /div

  9. Add z-index into Dexter’s snippet:

    #back {
    position: absolute;
    height: 100%;
    width: 100%;
    z-index:-1;
    }

  10. thanks a lot for this article. the solution provided by dubby was the one that helped me that i needed as i only wanted to apply the stretchy bg int a single div.

    i just wanted to post my version of the code because some of the things dubby suggested to put on it were actually keeping his solution from working on my site.

    here is what i ended up with

    #apoccomment {
    display:block;
    z-index:0;
    left:0px; right:0px;
    top:0px; bottom:0px;
    height:100%;
    }

    #bg {
    z-index:0;
    left:0px; top:0px;
    height:100%;
    background:url(“commentbg.jpg”);
    background-repeat: no-repeat;
    height:100%;}

    i removed the absolute positioning and only kept height since height was the only thing i wanted to stretch for my site. i could probably even get rid of the z-position lines but they don’t bother me. as long as it works i’m happy.

    my html was simply

    div id=”apoccomment”
    div id=”bg”
    content and more nested but irrelevent divs
    /div
    /div

    tested on FF 20014 and ie6.

  11. Hi. Thanks for this information. I’ve managed to stretch my background image. Can someone tell me why the content is not displaying on top of the background image? Is my code wrong?

    Untitled Document

    jkhjk

  12. Sorry here it is again without the html tags just the text….

    head
    style type “text/css”
    body {
    margin: 0px;
    padding: 0px;
    overflow: hidden;
    }

    #back {
    width: 100%;
    height: 100%;
    left: 0px;
    top: 0px;
    position: absolute;
    z-index: -1;
    }

    #content {
    position:absolute;
    z-index: 0;
    }
    /style
    /head
    body
    div id=”back” img src=”back.jpg” width=”100%” height=”600″/div
    div id=”content” table width=”100%” border=”0″ cellspacing=”0″ cellpadding=”0″
    tr
    tdjkhjktd
    tr
    /table
    /body
    /html

  13. What do i have to add in here to make my image stretch?

    body
    {
    background:444444
    url(‘http://img.jpg’) no-repeat fixed bottom;
    background-size:100%;
    color:white}

  14. If you are targeting a particular element of a document: This ‘fix’ will never work for firefox and godzillas alike. Because it will mes up your layout and you will be forced to use position absolute (folloowing this one) for every dodamn element of the page and give to each exact values of where they should be displayed MANUALLY. Or else your layout will become a total mess…

    But aas with everything else IE has a capability to achieve this marvelously within any given element by simply adding this line of code for your target element in CSS:

    filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src=’bg.gif’, sizingMethod=’scale’);

    this will same time give you, a transparency ready background element, since with this filter you can use PNG also while having it stretch exactly to the dimensions of your content element without a worry in casse you decide to later add/remove some content from it, because it will adapt to its new size generically.

    p.s.:
    The only scenario where using absolutely positioned elements (like solutions posted here) that try to force an image stretch to the desired dimensions and keep the content flowing uninterruptedly is the casse when you use it as a page background, that is: simulating a body background f.i. with very small gif stretched out to a smooth gradient background. Almost safe, but soon you will see that it isn’t that safe either.

    Sorry that Godzillas can’t digest IE code. (Nobody is to blame for them being extinct anyway). :)

  15. A simpler way to acheive this result is to not have the image in the background. Instead, it is placed on the webpage (like any other image) and everything else is layered on top of it using css.

    check out the link of how to do this here:

    http://localhost:15840/ArizonaHealthQuotes_0_02/

    (My opinion)
    Troy III said in his “fix” in the above post:

    “If you are targeting a particular element of a document: This ‘fix’ will never work for firefox and godzillas alike.”
    … AND
    “Sorry that Godzillas can’t digest IE code. (Nobody is to blame for them being extinct anyway)”

    I say:

    If it doesn’t work on both IE and Firefox.
    It doesn’t work. (<– period)

    Microsoft has learned their lesson that trying to push proprietery code fails. The proof is a steady loss of market share to firefox which now owns roughly 15% of the market. This is compared to roughly 5% just a few years ago.

    I claim they have learned their lesson because:

    Microsoft devs have publicly stated that IE 8 will support W3C standards (mainly focusing on css) in its default mode and will support IE specific hacks (for older sites) in quirks mode only.

    The web developer who wants to use IE specific hacks will have to specifically tell the IE 8 browser to run in quirks mode in the html syntax of the page.

    Information about this is available on blogs in microsoft’s dev center.

    This move by microsoft towards standards is somewhat a new face for the company.

    So my advise is to stay away from microsoft hacks to do this as it will not work for a significant amount of users to begin with and you may have to update your sites to get it to work with IE8 which is “schedualed” (don’t hold your breath) to come out in Q4 of this year.

  16. Sorry that link in the above post was something I was working on.

    The right link is:

    http://www.htmlite.com/faq022.php

  17. I am facing a strange problem. The images that are in my website stretch out a bit when i view in firefox. But the same images are perfect when viewed in IE. For this, the text that i have written on the images are not clean when viewed in firefox.Can anybody point out the problem.

  18. Also the same problem is not there when i test it in the localhost in any browsers. It started after i uploaded it in the main server

  19. What about shrinking?

  20. Thank you requiem4adream

  21. Hi….
    I have a problem…..my css is support in IE6 but not support in mozilla. Can you tell me any solution.

  22. >> I have a problem…..my css is support in IE6 but not support in mozilla.

    Then rewrite it. IE6 is an 8 year old browser, which hasn’t been updated in 4 years. There are 2 new versions of IE and many more standard-compliant browsers.

    Personally, I just dropped support for IE6.
    And I’m not alone…

    http://www.quirksmode.org/blog/archives/2009/02/to_hell_with_ba.html

  23. y’know there is an easier way to do this:

    background-position:center;

    so much easier !

  24. what should i add/remove here to make it stretch to any resolution? its 4 my blog.

    body {
    background-size: auto;
    background-position:center;
    background-image:url(http://upload.wikimedia.org/wikipedia/commons/1/13/Green_Grass.JPG);
    background-color: #000000 ;
    background-origin: content;
    background-attachment: fixed;
    /*background-repeat: repeat;*/
    color: #444;
    font: normal 62.5% “Lucida Sans Unicode”,sans-serif;
    margin: 0;
    padding: 0;
    }

  25. Mobile App Development

    the solution provided by dubby was the one that helped me that i needed as i only wanted to apply the stretchy bg int a single div.

    i just wanted to post my version of the code because some of the things dubby suggested to put on it were actually keeping his solution from working on my site.

    here is what i ended up with

    #apoccomment {
    display:block;
    z-index:0;
    left:0px; right:0px;
    top:0px; bottom:0px;
    height:100%;
    }

    #bg {
    z-index:0;
    left:0px; top:0px;
    height:100%;
    background:url(“commentbg.jpg”);
    background-repeat: no-repeat;
    height:100%;}

    i removed the absolute positioning and only kept height since height was the only thing i wanted to stretch for my site. i could probably even get rid of the z-position lines but they don’t bother me. as long as it works i’m happy.

    my html was simply

    div id=”apoccomment”
    div id=”bg”
    content and more nested but irrelevent divs
    /div
    /div

    tested on FF 20014 and ie6.

  26. Now all I need is a way to make background images work in Outlook :(

  27. Hello There!

    I have a problem with my repeater.jpg image in my CSS style sheet. It works fine in IE but it cuts off my image in Firefox. Is there anyway i can code it correctly so it works in both browsers.

    Here is my CSS Style Sheet Code:

    @charset “utf-8″;
    body {
    font-family: Helvetica, Arial, sans-serif;
    font-size: 12px;
    color: #333333;
    background-image: url(../images/repeater.jpg);
    background-repeat: repeat-x;
    margin-top: 0px;
    }
    #mainWrapper {
    width: 734px;
    margin-top: 0px;
    margin-right: auto;
    margin-left: auto;
    }
    #notice {
    background-color: #fffbef;
    padding-top: 5px;
    padding-bottom: 5px;
    border-top-width: 1px;
    border-bottom-width: 1px;
    border-top-style: solid;
    border-bottom-style: solid;
    border-top-color: #ede7c3;
    border-bottom-color: #EDE7C3;
    margin-top: 5px;
    margin-bottom: 5px;
    }

    h2 {
    font-weight: normal;
    }

    .style12 {
    color: #620000;
    font-size: 55px;
    }

    .style4 {
    font-size: 36px;
    color: #990000;
    font-weight: bold;
    }

    form {
    clear: both;
    padding: 0px 0px;
    }

    input[type=text] {
    border: 2px solid #dddddd;
    width:235px;
    padding-left: 5px;
    padding-bottom:5px;
    padding-top:5px;
    margin-left:-5px;
    font-size: 14px;
    clear: both;
    margin-bottom:5px;
    display: block;
    font-weight: bold;
    background: #f9f9f9;

    width: 98%;
    color: #444;
    }
    #footer {
    border-top-width: 1px;
    border-top-style: solid;
    border-top-color: #999999;
    padding-top: 10px;
    padding-bottom: 10px;
    margin-top: 20px;
    }
    input[type=text]:focus {
    border: 2px solid #65b3f9;
    }

    input[type=image] {
    display: block;
    margin: 0px auto;
    clear: both;
    }

    Any help much appreciated

    Thank you

  28. try this
    head section :)

    html, body {
    background: #000000 url(‘here u can type the image location exemple 1 : test.jpg or exemple 2 : http://imagelink.com/test1.jpg‘);
    background-repeat: no-repeat;
    background-attachment: fixed;
    background-size: 100%;
    }

  29. geez it’s doesn;t work ! did i make a fault ?

    body{line-height:1.5em;font-family:Arial, Helvetica, sans-serif;font-size:12px;color:#0d2d4b;margin:0;padding:0;background: #fff url(../images/nature_background.png) no-repeat fixed; background-size: auto; }

  30. hi, i need help to correct my background, i need it to stretch my background image “BACK.jpg” cause it tiled if you view it in firefox …. below code:

    ITMWISP

    html { overflow-y: hidden; }
    body { overflow-y: auto; }
    img#bg { position:absolute; z-index:-1; }
    #content { position:static; }

    body {
    color: #00FF00;
    font-size: 10px;
    font-family: GoblinMoon;
    background-color: #FFFFFF;
    background-image: url(“img/BACK.jpg”);
    background-repeat: no-repeat;
    background-attachment: fixed;
    background-size: 100%;
    }

  31. Thanks for this! you saved my blog from a messy layout! :)

  32. Hii,, Nice review there is som many review out there, but your site still in the front of my choice.

  1. Pingback: Lounge KAORI: Kaorin no Kyoukai "GARden of SaiMaho" - Ngobrol dan Kenalan disini yuk - Page 82 - KAORI - Komunitas Anime Otaku Rakyat Indonesia Forum

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 27 other followers

%d bloggers like this: