在背景中拉伸和缩放 CSS 图像——只用 CSS

I want that my background image stretch and scale depending on the browser viewport size.

I've seen some questions on Stack Overflow that do the job, like Stretch and scale CSS background for example. It works well, but I want to place the image using background, not with an img tag.

In that one an img tag is placed, and then with CSS we tribute to the img tag.

width:100%; height:100%;

It works, but that question is a bit old, and states that in CSS 3 resizing a background image will work pretty well. I've tried this example the first one, but it didn't work out for me.

Is there a good method to do it with the background-image declaration?

转载于:https://stackoverflow.com/questions/1150163/stretch-and-scale-a-css-image-in-the-background-with-css-only

weixin_41568126
乱世@小熊 Tomorrow I will start a question on meta.stackoverflow.com about the best course of action for this question, I will post the link here for anyone to follow. Thank you for the input, always welcome.
4 年多之前 回复
weixin_41568126
乱世@小熊 Many questions like this float around SO. In this one, it's funny the amount of people who comment with their "two cents" about current CSS3 solutions, and don't realize that it was asked when CSS3 wasn't heavily implement and standardized across browsers. It surely is a cry out for more current answer. Also there are a couple more issues with the question, due to my understanding of the subject on the time I wrote it.
4 年多之前 回复
weixin_41568126
乱世@小熊 Of course not, me neither.
4 年多之前 回复
csdnceshi65
larry*wei IMHO we wouldn't want to close the question with the best answers and instead encourage duplicates to link to it. I'm sure this would have been discussed on Meta but I can't find it now...
4 年多之前 回复
weixin_41568126
乱世@小熊 Shouldn't age of the question be a factor? This one was asked 6 years ago and the question you've point out was asked 4 years ago.
4 年多之前 回复
csdnceshi65
larry*wei Possible duplicate of CSS background image to fit width, height should auto-scale in proportion
4 年多之前 回复
csdnceshi66
必承其重 | 欲带皇冠 Maybe this demo can be helpful: w3schools.com/cssref/…
5 年多之前 回复
weixin_41568174
from.. background-size: 100% 100%;
大约 6 年之前 回复

18个回答

CSS3 has a nice little attribute called background-size:cover.

This scales the image so that the background area is completely covered by the background image whilst maintaining aspect ratio. The entire area will be covered however part of the image may not be visible if the width/height of the resized image is too great

csdnceshi67
bug^君 Aside of using background-size:cover... Don't forget to use services like ImageBoss to generate your images responsively. It would reduce your load time/page speed considerably.
2 年多之前 回复
csdnceshi70
笑故挽风 If you want this, but only for the horizontal axis, use this: background-size: 100% auto; stackoverflow.com/questions/41025630/…
2 年多之前 回复
csdnceshi74
7*4 try: background-size: cover; -ms-background-size: cover; -o-background-size: cover; -moz-background-size: cover; -webkit-background-size: cover;
2 年多之前 回复
csdnceshi78
程序go It doesn't seem to work on Firefox. However, background-size: 100vw 100vh;does the trick nicely.
2 年多之前 回复
csdnceshi75
衫裤跑路 in case you you want it to work in IE browsers - github.com/louisremi/background-size-polyfill
大约 6 年之前 回复
weixin_41568134
MAO-EYE background-size: cover does not seem to work for iPad Safari
6 年多之前 回复
csdnceshi61
derek5. Cover crops the image if the aspect ratio doesn't match, so it's not a good general solution.
7 年多之前 回复

CSS:

html,body {
    background: url(images/bg.jpg) no-repeat center center fixed;
    -webkit-background-size: cover; /* For WebKit*/
    -moz-background-size: cover;    /* Mozilla*/
    -o-background-size: cover;      /* Opera*/
    background-size: cover;         /* Generic*/
}
csdnceshi75
衫裤跑路 On Android it worked for when using html, body {...} instead of body {...}.
4 年多之前 回复
csdnceshi52
妄徒之命 However, this doesn't work in IE8. It creates a margin on the top and bottom of the window.
6 年多之前 回复

Using the code I mentioned...

HTML

<div id="background">
    <img src="img.jpg" class="stretch" alt="" />
</div>

CSS

#background {
    width: 100%; 
    height: 100%; 
    position: fixed; 
    left: 0px; 
    top: 0px; 
    z-index: -1; /* Ensure div tag stays behind content; -999 might work, too. */
}

.stretch {
    width:100%;
    height:100%;
}

That produces the desired effect: only the content will scroll, not the background.

The background image resizes to the browser viewport for any screen size. When the content doesn't fit the browser viewport, and the user needs to scroll the page, the background image remains fixed in the viewport while the content scrolls.

With CSS 3 it seems this would be a lot easier.

weixin_41568126
乱世@小熊 The obvious mistake people do is to put the background image in the css (ie by background : url("example.png");) and then use the css attribute background-size:100%; beneath it to hopefully scale the image to screen width. This will not work, Will it? If you wish to put a background image for the body then an image attribute should be added to the body tag like <body background="example.png">. Then use css background-size:100%; to scale it.
5 年多之前 回复
csdnceshi67
bug^君 The issue I am having is with IE8. The background image of a DIV stretches full but in IE8 the images goes outside the DIV hence not being able to see the full image. It gets cropped out. Here is my question: stackoverflow.com/questions/22331179/…
6 年多之前 回复
csdnceshi65
larry*wei z-index: -1; keeps your image in the background. If you desire to show your image in the foreground, you can either increase the z-index value or remove that index.
接近 7 年之前 回复
csdnceshi56
lrony* no need for the class="stretch", just use #background img {} as identifier in the css
大约 8 年之前 回复
weixin_41568110
七度&光 But this is not background image. You can only do this to a block, but not a inline element such as a input[type=text]. Or am I wrong?
接近 9 年之前 回复

You could use the CSS3 property to do it quite nicely. It resizes to ratio so no image distortion (although it does upscale small images). Just note, it's not implemented in all browsers yet.

background-size: 100%;
weixin_41568184
叼花硬汉 if your browser doesnt support it you can always use modernizr and poylfills..
7 年多之前 回复
csdnceshi67
bug^君 It's also advisable to add auto to preserve aspect ratio.
接近 8 年之前 回复
csdnceshi75
衫裤跑路 To preserve the aspect ratio of the image you should use "background-size: cover;" or "background-size: contain;". I've built a polyfill that implements those values in IE8: github.com/louisremi/background-size-polyfill
接近 8 年之前 回复
weixin_41568196
撒拉嘿哟木头 That pretty much is the full code! Create a container with a background-image and include the property above. As mentioned, browser support is not good yet and there are browser specific versions of this ie. -webkit-background-size etc. See W3C CSS3 Module: background-size and css3.info: background-size
9 年多之前 回复

I use this, and it works with all browsers:

<html>
    <head>
        <title>Stretched Background Image</title>
        <style type="text/css">
            /* Remove margins from the 'html' and 'body' tags, and ensure the page takes up full screen height. */
            html, body {height:100%; margin:0; padding:0;}

            /* Set the position and dimensions of the background image. */
            #page-background {position:fixed; top:0; left:0; width:100%; height:100%;}

            /* Specify the position and layering for the content that needs to appear in front of the background image. Must have a higher z-index value than the background image. Also add some padding to compensate for removing the margin from the 'html' and 'body' tags. */
            #content {position:relative; z-index:1; padding:10px;}
        </style>
        <!-- The above code doesn't work in Internet Explorer 6. To address this, we use a conditional comment to specify an alternative style sheet for IE 6. -->
        <!--[if IE 6]>
        <style type="text/css">
            html {overflow-y:hidden;}
            body {overflow-y:auto;}
            #page-background {position:absolute; z-index:-1;}
            #content {position:static;padding:10px;}
        </style>
        <![endif]-->
    </head>
    <body>
        <div id="page-background"><img src="http://www.quackit.com/pix/milford_sound/milford_sound.jpg" width="100%" height="100%" alt="Smile"></div>
        <div id="content">
            <h2>Stretch that Background Image!</h2>
            <p>This text appears in front of the background image. This is because we've used CSS to layer the content in front of the background image. The background image will stretch to fit your browser window. You can see the image grow and shrink as you resize your browser.</p>
            <p>Go on, try it - resize your browser!</p>
        </div>
    </body>
</html>
background-size: 100% 100%; 

stretches bg to fill entire element on both axis

You can add this class into your CSS file.

.stretch {
            background: url(images/bg.jpg) no-repeat center center fixed;
            -webkit-background-size: cover;
            -moz-background-size: cover;
            -o-background-size: cover;
            background-size: cover;
}

It works in:

  • Safari 3 or later
  • Chrome Whatever or later
  • Internet Explorer 9 or later
  • Opera 10 or later (Opera 9.5 supported background-size, but not the keywords)
  • Firefox 3.6 or later (Firefox 4 supports non-vendor prefixed version)
csdnceshi61
derek5. This is a working "stretch to fit" answer. Note: aspect ratio will change.
大约 3 年之前 回复

You can actually achieve the same effect as a background image with the img tag. You just have to set its z-index lower than everything else, set position:absolute and use a transparent background for every box in the foreground.

csdnceshi71
Memor.の Just found this other post which references the use of the proprietary MS AlphaImageLoader: stackoverflow.com/questions/2991623/…
接近 9 年之前 回复
csdnceshi75
衫裤跑路 Being CSS3, there is nothing wrong with using a property that the most modern browsers see and giving a minimum standard to unsupported browsers. Here, for example, you might be able to use a boring but acceptable tiled background for <IE8 and a lovely picture for Firefox/Chrome/Safari/Opera. Also, there are many polyfills to replicate CSS3 functionality in older browsers with JavaScript. In other words, you don't need to wait for every browser to support CSS3 in order to use it.
9 年多之前 回复
csdnceshi72
谁还没个明天 There might be and taking into account developments in browser usage, you might be able to use them commercially in only...10 year?
大约 11 年之前 回复
csdnceshi64
游.程 Thats what i saw in others SO questions, and works, but since CSS3 as come out, i thought that now was a better way to to it.
大约 11 年之前 回复

Explained by css-tricks https://css-tricks.com/perfect-full-page-background-image/

demo : https://css-tricks.com/examples/FullPageBackgroundImage/progressive.php

code :

body { 
  background: url(images/myBackground.jpg) no-repeat center center fixed; 
  -webkit-background-size: cover;
  -moz-background-size: cover;
  -o-background-size: cover;
  background-size: cover;
}
csdnceshi75
衫裤跑路 based on above answer, I have seen background attachment fix does not work on mobile devices and microsoft edge. The perfect solution to make background stretch and fix on all devices and browsers I recommend jquery-backstretch.com
接近 2 年之前 回复

Thanks!

But then it was not working for the Google Chrome and Safari browsers (stretching worked, but the hight of the pictures was only 2 mm!), until someone told me what lacks:

Try to set height:auto;min-height:100%;

So change that for your height:100%; line, gives:

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

.stretch {
    width:100%;
    height:auto;
    min-height:100%;
}

Just before that newly added code I have this in my Drupal Tendu themes style.css:

html, body{height:100%;}

#page{background:#ffffff; height:auto !important;height:100%;min-height:100%;position:relative;}

Then I have to make a new block within Drupal with the picture while adding class=stretch:

< img alt="" class="stretch" src="pic.url" />

Just copying a picture with the editor in that Drupal block doesn't work; one has to change the editor to non-formatted text.

共18条数据 1 尾页
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐