简体   繁体   English

拉伸图像

[英]Stretching image

I have a wrapper div that contains arbitrary content (I don't know its length). 我有一个包含任意内容的包装div (我不知道它的长度)。 How can I put a background image that stretches its whole length since background-images doesn't stretch? 由于背景图像不会伸展,我怎样才能放置一个延伸其整个长度的背景图像?

I've tried with a div containing a img tag. 我试过一个包含img标签的div The div has a lover z-index that the rest of the content and has position: absolute . div有一个情人z-index,其余的内容和position: absolute The problem is that the image is longer that the content and so it just makes it longer (the wrapper has overflow: auto ). 问题是图像比内容长,所以它只是使它更长(包装器overflow: auto )。

<div id="wrapper">
    <div id="image-wrapper" style="position: absolute"><img src="bg.jpg"></div>
    [.. OTHER CONTENT ..]
</div>

If I set the div and the image's width and height to 100%, it takes the window's height, not the wrapper's. 如果我将div和图像的宽度和高度设置为100%,则需要窗口的高度,而不是包装器的高度。

Any help? 有帮助吗?

background-size is available since CSS3: CSS3以后可以使用background-size

#image {
  background-image: url("bg.png");
  background-size: auto;
}

auto is the default value and does not stretch the image. auto是默认值,不会拉伸图像。

You can set the width and height manually: 您可以手动设置宽度和高度:

#image {
  background-size: 100% 100%;
}

or 要么

#image {
  background-size: 500px 300px;
}

The alternative: background-size: contain and background-size: cover . 替代方案: background-size: containbackground-size: cover

contain stretches the image so that the image is as big as possible but completely visible within the element, whereas cover stretches the image to 100% width, regardless if the image is cropped at the top and/or the bottom. contain拉伸图像,使图像尽可能大,但在元素内完全可见,而cover将图像拉伸到100%宽度,无论图像是在顶部和/或底部裁剪。

But the different browsers are not completely consistent when rendering backgrounds with these keywords. 但是,在使用这些关键字渲染背景时,不同的浏览器并不完全一致。

If you are willing to use JavaScript, check out Supersized . 如果您愿意使用JavaScript,请查看Supersized It seems to work well for this particular case. 它似乎适用于这种特殊情况。

你也可以尝试在图像上使用html5方法。

#image-wrapper img {max-width: 100%}

Add position: relative to the styles for #wrapper . 添加position: relative对于#wrapper的样式。

http://css-tricks.com/absolute-positioning-inside-relative-positioning/ http://css-tricks.com/absolute-positioning-inside-relative-positioning/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM