在div元素中显示图像的一部分

时间:2016-12-21 10:24:15

标签: html css image

当我有一个例如300 * 300px的div和一个1280 * 560px的图像时。 我可以在我的div中显示图像的特定部分,同时仅使用html / css保持响应吗?

div总是占据页面宽度的33%

我的代码如下:

HTML

<div class="crop">
    <img src="path/to/img">
</div>

CSS

position: relative;
overflow: hidden;
min-height: 300px;

3 个答案:

答案 0 :(得分:2)

使用背景图片可能会在这种情况下帮助您,您可以使用background-position调整其位置:

.crop{
  position: relative;
  overflow: hidden;
  min-height: 300px;
  width: 300px;
  background-image: url(https://cdn.pixabay.com/photo/2015/07/06/13/58/arlberg-pass-833326_960_720.jpg);
  background-size: contain;
}
<div class="crop">
</div>

答案 1 :(得分:1)

是的,事实很简单:

.image {
display: block;
position: relative;
overflow: hidden;
width: 300px;
height: 300px;
}

.image img {
position: relative;
left: -100px;
top: -100px;
}

<div class="image">
    <img src="http://img05.deviantart.net/c135/i/2011/134/7/0/bridge_by_kzonedd-d3gcetc.jpg" alt="photo of old wooden bridge" />
</div>

当然,减去100px只是为了向您展示如何定位。玩弄价值观,一切都会变得清晰。

HTH。祝你好运,玩得开心。

答案 2 :(得分:0)

是的,你可以用flex

做到这一点

这是代码,下面的解释

div{
width:300px;
height:300px;
overflow:hidden;
position:relative;
left:50%;
transform:translateX(-50%);
display:flex;
justify-content:center;
align-items:center;
}
div img{
flex:0;
width:auto;
min-height:100%;}
<div>
  <img src ="http://www.cooperindustries.com/content/dam/public/safety/notification/products/Mass%20Notification%20Systems/Spotlight/MNS_WideArea_Spotlight3.jpg">
</div>

在justify-content上你可以放置flex-start,flex-end和center以适合你想要水平输入的部分

在对齐项目上,您可以使用相同的内容来证明内容可以垂直调整。

此图像是风景,所以我设置最小高度100%和宽度自动,当你有一个肖像图像时,你可以做另一面。如果图像是方形的,宽度100%就可以了。

相关问题