我希望我的背景图像拉伸和缩放取决于浏览器视口的大小。
我在Stack Overflow上看到过一些问题,比如拉伸和缩放CSS背景。它工作得很好,但我想使用背景放置图像,而不是使用img标签。
在其中放置了一个img标签,然后用CSS向img标签致敬。
width:100%; height:100%;
它的工作,但这个问题有点老了,并指出在css3调整背景图像的大小将工作得很好。我已经尝试了第一个例子,但它不适合我。
是否有一个好的方法来做背景图像声明?
我希望我的背景图像拉伸和缩放取决于浏览器视口的大小。
我在Stack Overflow上看到过一些问题,比如拉伸和缩放CSS背景。它工作得很好,但我想使用背景放置图像,而不是使用img标签。
在其中放置了一个img标签,然后用CSS向img标签致敬。
width:100%; height:100%;
它的工作,但这个问题有点老了,并指出在css3调整背景图像的大小将工作得很好。我已经尝试了第一个例子,但它不适合我。
是否有一个好的方法来做背景图像声明?
当前回答
您可以使用CSS3属性很好地做到这一点。它会根据比例调整大小,因此不会产生图像失真(尽管它会放大小图像)。请注意,它还没有在所有浏览器中实现。
background-size: 100%;
其他回答
我希望将背景图像居中并缩放,而不是将其拉伸到整个页面,并且我希望保持纵横比。这对我来说很管用,多亏了其他答案中提出的变化:
内联图片:------------------------
<div id="background">
<img src="img.jpg" class="stretch" alt="" />
</div>
CSS ----------------------------------
html {
height:100%;
}
#background {
text-align: center;
width: 100%;
height: 100%;
position: fixed;
left: 0px;
top: 0px;
z-index: -1;
}
.stretch {
margin: auto;
height:100%;
}
background-size: 100% 100%;
拉伸背景以填充两个轴上的整个元素。
使用下面的CSS:
背景尺寸:100% 100%
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*/
}
这是由CSS技巧解释的:完美的全页面背景图像
演示:https://css-tricks.com/examples/FullPageBackgroundImage/progressive.php
代码:
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;
}