首页 文章

响应的背景图像与响应的高度和宽度

提问于
浏览
0

我试图让这些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 回答

  • 0

    你有 max-width: 500px ,然后用 background-size: cover 覆盖它 . 如果你想使用 background-size: cover ,你应该在 div 中放置第二个 div 并在嵌套的 div 上使用该 background-size: cover 样式,以便它覆盖父 div ,其最大宽度为500px .

    例如:

    <div class="parent">
      <div class="child">
      </div>
    </div>
    
    .parent {max-width: 500px}
    .child {background-size: cover; //include image}
    

    没有测试代码,但你得到了它的要点 .

相关问题