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

相關文章
相關標籤/搜索