从顶部裁剪图像

Lev*_*Lev 2 css

通过设置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>
Run Code Online (Sandbox Code Playgroud)

有没有办法从顶部裁剪图像?如果正在调整窗口大小并且图像不再适合容器的高度,则应从顶部而不是从底部裁剪图像。

Sco*_*ott 5

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

然后添加position: absolute; bottom: 0;到图像本身:

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

.img {
	    display: block;
        width: 100%;
        height: auto;
        position: absolute;
        bottom: 0;
    }
Run Code Online (Sandbox Code Playgroud)
<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" />
Run Code Online (Sandbox Code Playgroud)