如何使<div>与背景图像保持动态高度</div>

时间:2015-04-05 21:29:17

标签: javascript jquery html css

我需要使用背景图像来模仿div的以下行为。

页面上有3个div。它们的最大宽度为600px。 在较小的屏幕上打开时,宽度会调整到屏幕,高度也应调整,保持图像的宽高比始终为10/7

我尝试使用background-size样式属性,但这不会改变div的高度,因此图片最终会被剪裁。我无法剪辑图像。

请告知

一个 enter image description here

2 enter image description here

3 enter image description here

3 个答案:

答案 0 :(得分:2)

嗯,实际上这取决于你的真实标记,但这可能是一个起点:

关键点是,top/bottom padding上的百分比值相对于包含该框的框的width

此外,使用background-size: contain调整背景图像的宽高比。值得注意的是,IE9 +支持此功能。

有关响应式容器的进一步阅读,请参阅我的回答here

<强> Example Here

&#13;
&#13;
.box {
  background: url(http://placehold.it/300) 50% 50% / contain no-repeat;
  
  width: 80%; /* or whatever else */
  overflow: hidden;
  position: relative;
}

.box > span {
  position: absolute;
  top: 0; right: 0; bottom: 0; left: 0;
  padding: 5% 0;
}

.box > span:before,
.box > span:after {
  content: "";
  position: absolute;
  left: 0; right: 0;
  padding: 2% 0;
}

.box > span:before {
  top: 0;
  background-color: rgb(255, 90, 79);
}

.box > span:after {
  bottom: 0;
  background-color: rgb(159, 31, 56);
}

.box:before {
  content: "";
  display: block;
  padding-bottom: 70%;
}
&#13;
<div class="box">
  <span>
    Lorem ipsum dolor sit amet, consectetur adipisicing elit. Debitis dolores doloremque id quia esse! Doloribus voluptate nihil quam natus, similique, vero amet nesciunt excepturi. Optio dicta quas, dolores facere voluptatem.
  </span>
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

如果您的div仅用于显示此图像,则可以使用此css“技巧”

来完成

div{
  background: url(http://gogoodscout.com/blog/wp-content/uploads/2015/02/Do-YOu-Feel-Good.jpg);
  width: 100%;
  padding-bottom: 49%;
  background-size: cover;
}
<div></div>

注意如果调整填充以反映宽高比,div将始终具有图像的宽高比。

答案 2 :(得分:1)

这个技巧可以帮到你:

#container{
  
background-image:url("http://cdn4.colorlib.com/wp/wp-content/uploads/sites/2/2014/02/Olympic-logo.png"); 
  background-size:cover;
  }

#ghostImg{
  width:100%;
  visibility:hidden;
  }
<div id="container">
  <img src="http://cdn4.colorlib.com/wp/wp-content/uploads/sites/2/2014/02/Olympic-logo.png" id="ghostImg"/>
  </div>