How to extend an image in css to cover the full width of the page?

时间:2015-05-24 21:17:57

标签: css css3

I have an image which is just a color transition image (dark blue to light blue) but it has a couple of graphic blocks on the left side.

I'm using width: 100% so that the image will be stretched from the left side of the page all the way to the right side of the page and this works fine.

However, when the browser window is narrower than the page, the image always stops on the far right side of the browser window. Then when I move the horizontal scroll bar to the right, the image is not stretched across the page. It stops exactly where the browser window stopped.

CSS:

#header {
    height:205px;
    width:100%;
    min-width:100%;
    background-position:left top;
    background-image:url(images/header.jpg);
    background-repeat:no-repeat;
    -webkit-background-size:cover;
    -moz-background-size:cover;
    -o-background-size:cover;
    background-size:cover;
}

I've tried width: auto and various combinations of width and min-width: auto and 100%. In all cases, when I scroll to the right, the image always stops where the browser window right side was originally. If I stretch the browser window wide enough to show the whole page, then the image shows as it should, coverring the full width. When I shrink the browser window to half the width of the page, then the image is only covering half the page (the part showing in the browser window). Then when I scroll right, the image is not stretched to cover the full page width any more.

How to do get an image to cover the full 100% of the page width even if the browser window has a horizontal scroll bar (is unable to show the full page without scrolling right)?

1 个答案:

答案 0 :(得分:0)

You can use vw css units which refer to a pecentage of the viewport width. so 100vw = 100% width of viewport.

#header {
    height:205px;
    width: 100%; /* fall back */
    width: 100vw;
    background-position:left top;
    background-image:url(images/header.jpg);
    background-repeat:no-repeat;
    -webkit-background-size:cover;
    -moz-background-size:cover;
    -o-background-size:cover;
    background-size:cover;
}