首页 文章

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

提问于
浏览
1

当我有一个div,例如300 * 300px和一个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

    是的,事实很简单:

    .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只是为了向您展示如何定位 . 玩弄 Value 观,一切都会变得清晰 .

    HTH . 祝好运并玩得开心点 .

  • 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

    是的,你可以用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%就可以了

相关问题