是否有一种方法来获得CSS的背景拉伸或缩放以填充它的容器?
当前回答
目前还没有。它将在CSS 3中可用,但要在大多数浏览器中实现还需要一段时间。
其他回答
使用CSS缩放图像是不太可能的,但是可以通过以下方式实现类似的效果。
使用下面的标记:
<div id="background">
<img src="img.jpg" class="stretch" alt="" />
</div>
使用以下CSS:
#background {
width: 100%;
height: 100%;
position: absolute;
left: 0px;
top: 0px;
z-index: 0;
}
.stretch {
width:100%;
height:100%;
}
你该结束了!
为了将图像缩放为“完全出血”并保持纵横比,你可以这样做:
.stretch { min-width:100%; min-height:100%; width:auto; height:auto; }
它的效果非常好!然而,如果裁剪一个维度,它将只在图像的一侧裁剪,而不是在两侧均匀裁剪(并居中)。我已经在Firefox、Webkit和Internet Explorer 8中测试了它。
对于现代浏览器,你可以通过使用background-size来实现:
body {
background-image: url(bg.jpg);
background-size: cover;
}
覆盖意味着垂直或水平拉伸图像,这样它就不会平铺/重复。
这适用于Safari 3(或更高版本)、Chrome、Opera 10+、Firefox 3.6+和Internet Explorer 9(或更高版本)。
为了让它在低版本的ie浏览器中工作,可以尝试以下CSS:
filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src='.myBackground.jpg', sizingMethod='scale');
-ms-filter: "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='myBackground.jpg', sizingMethod='scale')";
我想指出,这相当于做:
html { width: 100%; height: 100%; }
body { width: 100%; height: 100%; /* Add background image or gradient to stretch here. */}
试试这个
http://jsfiddle.net/5LZ55/4/
body
{
background: url(http://p1.pichost.me/i/40/1639647.jpg) no-repeat fixed;
background-size: cover;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
}
SolidSmile作弊的另一个技巧是通过设置宽度和自动设置高度来缩放(按比例重新调整大小)。
Ex:
#background {
width: 500px;
height: auto;
position: absolute;
left: 0px;
top: 0px;
z-index: 0;
}
推荐文章
- 使伸缩项目正确浮动
- 如何取消最大高度?
- 形式内联内的形式水平在twitter bootstrap?
- 自定义元素在HTML5中有效吗?
- 如何选择在最后一个子元素之前的元素?
- 如何触发自动填充在谷歌Chrome?
- CSS变换,锯齿边缘在铬
- 创建圈div比使用图像更容易的方法?
- 强迫孩子服从父母的弯曲边界在CSS
- 为什么Chrome浏览器不正确地确定页面是在不同的语言,并提供翻译?
- 在CSS中@apply是什么?
- 在网页上用鼠标模拟震颤(例如帕金森病)?
- Bootstrap抛出Uncaught错误:Bootstrap的JavaScript需要jQuery
- 如何改变文本区域的边框颜色:焦点
- 我如何设置背景颜色为文本的宽度,而不是整个元素的宽度,使用CSS?