CSS实现宽度自适应100%,宽高16:9的比例的圖片或者矩形

前言

图片的大小是多少,宽度必定,高度要始终自自适应为16:9。css

 

解决

1经过js,程序算出绝对高度再进行设置。这是解决问题最容易想到的方法。spa

2.咱们的原则是能用css实现的功能尽可能用css,这有利于后期项目的维护。3d

css一样能够实现这个问题,咱们能够利用边距的百分比属性定义来优雅实现。code

 

咱们经过百分比设置宽度,根据宽度的比例数值*9/16,计算出高度的百分比数值,blog

设置内边距为高度的数值,最后用绝对定位把图片百分百填充到咱们设置的区域里面图片

代码

HTMLit

<div class="box">
  <div class="scale">
    <img src="http://img17.3lian.com/201612/16/88dc7fcc74be4e24f1e0bacbd8bef48d.jpg" class="item"/>
  </div>
</div>

cssio

.box {
  width: 80%;
}

.scale {
  width: 100%;
  padding-bottom: 56.25%;
  height: 0;
  position: relative;
}

.item {
  width: 100%;
  height: 100%;
  background-color: aquamarine;
  position: absolute;
}

然後就能够了。。。。嘻嘻class

相关文章
相关标签/搜索