2016-12-12 202 views
0

通過設置圖像容器的overflow: hidden屬性可以非常容易地從底部,左側或右側裁剪圖像。從頂部裁剪圖像

<div class="img-container"> 
    <img class="img" src="/img.jpg" /> 
</div> 

<style> 
    .img-container { 
     overflow: hidden; 
     max-height: 700px; 
    } 

    .img { 
     width: 100%; 
     height: auto; 
    } 
</style> 

有沒有辦法從頂部裁剪圖像?如果窗口正在調整大小,並且圖像不再適合容器的高度,則應從頂部而不是從底部對圖像進行裁剪。

+1

試'位置:絕對;底部:0;' –

+0

這工作,謝謝! – Lev

+0

很高興幫助! –

回答

2

position: relative;添加到div容器(和高度)。

然後加入position: absolute; bottom: 0;到圖像本身:

.img-container { 
 
     overflow: hidden; 
 
     height: 100px; 
 
     max-height: 300px; 
 
     position: relative; 
 
    } 
 

 
.img { 
 
\t  display: block; 
 
     width: 100%; 
 
     height: auto; 
 
     position: absolute; 
 
     bottom: 0; 
 
    }
<div class="img-container"> 
 
    <img class="img" src="http://placekitten.com/400/500" /> 
 
</div> 
 

 
<p>Full image below</p> 
 
    <img src="http://placekitten.com/400/500" />

1

另一種選擇是將所述圖像作爲背景,然後將其定位在容器的底部。適用background-size保持縱橫比:

.img-container { 
 
    height: 100px; 
 
    width: 100px; 
 
    background: url(http://placekitten.com/400/500) no-repeat bottom; 
 
    background-size: 100% auto; 
 
}
<div class="img-container"></div>