如何使用background-image创建div就像<img "width="100%&#34;/"/>一样

时间:2016-03-19 14:53:12

标签: css background-image background-size

我有这段代码:

&#13;
&#13;
div#fond {
  background-image: url('https://www.thetileapp.com/images/Purse_Tabletop-46.jpg');
  background-size: cover;
  height: 100%;
  width: 100%;
}
&#13;
<!DOCTYPE html>
<html>
<body>
  <div id="fond">
    ABCD
  </div>
  <br>
  <img src="https://www.thetileapp.com/images/Purse_Tabletop-46.jpg" width="100%" />
</body>

</html>
&#13;
&#13;
&#13;

如何使div具有与img相同的行为,以便div的高度适应窗口的宽度。 目前,高度适合于div内容。

1 个答案:

答案 0 :(得分:3)

要使百分比高度起作用,您必须添加html, body {height: 100%;},否则浏览器将无法计算默认值auto的百分比。百分比高度基于parnet工作,当父级是body / html时,你需要添加我提到的规则。

或者,您可以使用视口单元(vw / vh),例如:

div#fond {
  background-image: url('https://www.thetileapp.com/images/Purse_Tabletop-46.jpg');
  background-size: cover;
  height: 100vh;
  width: 100vw;
}
相关问题