跳到主要內容

RWD情況下,讓圖片維持固定比例縮放

固定圖片比例為 16:9,寬高比為 1:0.5625
首先設定 .box:after 內容 padding-top:56.25%,設定為 16:9 的比例,並且設定 content 為空的,然後定義 display 為 block,把空間撐出來 接著設定圖片的內容,如同圖片水平垂直置中設定過的參數,在設定一次,同時也別忘了 .box 要設定為 position:relative 這樣就可以達到固定比例的圖片(即使圖片不是 16:9 的比例),最後也別忘了要加上 overflow:hidden,讓圖片不會超出 box 的大小

HTML
<div class='box'>
    <img class='img' src='http://placeimg.com/800/600'/>
</div>
<div class='box'>
    <img class='img' src='http://placeimg.com/600/800'/>
</div>
<div class='box'>
    <img class='img' src='http://placeimg.com/160/90'/>
</div>

CSS
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
.box {
background:#ccc;
position:relative;
overflow:hidden;
margin: 20px;
}
.box:after {
padding-top: 56.25%;
content:"";
display: block;
}
.img {
position:absolute;
top:0;
bottom:0;
right:0;
left:0;
max-width:100%;
margin:auto;
}

若是600:400的比例,則是改為 padding-top :66.66%;



資料來源:
https://blog.shinychang.net/2014/03/10/%E5%9B%BA%E5%AE%9A%E6%AF%94%E4%BE%8B%E9%9F%BF%E6%87%89%E5%BC%8F%E5%9C%96%E7%89%87/