我试图让这些div最大500px乘500px . 即使设置max-width和max-height属性,它仍会占用整个页面加上一些高度 . 我希望背景图像能够响应并保持其纵横比 . 我读到如果你将高度除以宽度然后乘以100,你得到用作padding-top属性的百分比 . 在我的情况下,500/500是1并且乘以100很好,100% . 任何帮助或建议将不胜感激 .
HTML:
<html>
<body>
<div></div>
<div></div>
</body>
</html>
CSS:
body {
width: 80%;
height: 100%;
}
div {
width: 40%;
max-width: 500px;
padding-top: 100%;
background-image: url(http://placehold.it/500x500);
background-repeat: no-repeat;
background-position: center center;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
margin: 2.5%;
float: left;
}
1 回答
你有
max-width: 500px
,然后用background-size: cover
覆盖它 . 如果你想使用background-size: cover
,你应该在div
中放置第二个div
并在嵌套的div
上使用该background-size: cover
样式,以便它覆盖父div
,其最大宽度为500px .例如:
没有测试代码,但你得到了它的要点 .