Stretch and scale CSS background

2018-12-31 04:37发布

Is there a way to get a background in CSS to stretch or scale to fill its container?

标签: html css
16条回答
低头抚发
2楼-- · 2018-12-31 04:58

Define "stretch and scale"...

If you've got a bitmap format, it's generally not great (graphically speaking) to stretch it and pull it about. You can use repeatable patterns to give the illusion of the same effect. For instance if you have a gradient that gets lighter towards the bottom of the page, then you would use a graphic that's a single pixel wide and the same height as your container (or preferably larger to account for scaling) and then tile it across the page. Likewise, if the gradient ran across the page, it would be one pixel high and wider than your container and repeated down the page.

Normally to give the illusion of it stretching to fill the container when the container grows or shrinks, you make the image larger than the container. Any overlap would not be displayed outside the bounds of the container.

If you want an effect that relies on something like a box with curved edges, then you would stick the left side of your box to the left side of your container with enough overlap that (within reason) no matter how large the container, it never runs out of background and then you layer an image of the right side of the box with curved edges and position it on the right of the container. Thus as the container shrinks or grows, the curved box effect appears to shrink or grow with it - it doesn't in fact, but it gives the illusion that is what's happening.

As for really making the image shrink and grow with the container, you would need to use some layering tricks to make the image appear to function as a background and some javascript to resize it with the container. There's no current way of doing this with CSS...

If you're using vector graphics, you're way outside my realm of expertise I'm afraid.

查看更多
若你有天会懂
3楼-- · 2018-12-31 05:03

In one word: no. The only way to stretch an image is with the <img> tag. You'll have to be creative.

This used to be true in 2008, when the answer was written. Today modern browsers support background-size which solves this problem. Beware that IE8 doesn't support it.

查看更多
泪湿衣
4楼-- · 2018-12-31 05:09

Try the article background-size. If you use all of the following, it will work in most browsers except Internet Explorer.

.foo {
    background-image: url(bg-image.png);
    -moz-background-size: 100% 100%;
    -o-background-size: 100% 100%;
    -webkit-background-size: 100% 100%; 
    background-size: 100% 100%;
} 
查看更多
梦醉为红颜
5楼-- · 2018-12-31 05:12

I would like to point out that this is equivalent to doing:

html { width: 100%; height: 100%; }
body { width: 100%; height: 100%; /* Add background image or gradient to stretch here. */}
查看更多
登录 后发表回答