【问题标题】:Center image inside div + resize and keep proportion of image在 div 中居中图像 + 调整大小并保持图像的比例
【发布时间】:2018-12-19 18:30:34
【问题描述】:

我试图在 div 内垂直居中图像 - 同时保持原始图像的比例并且只允许它位于 div 内。

原始图像源会动态变化 - 理论上可以是任何尺寸:200x150、500x100、500x500 等。

到目前为止,我所拥有的是:

.outer {
    position: relative;
    background: gray;
    width: 200px;
    height: 150px;
}

.inner {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    background: gold;
    overflow: hidden;
    width: 200px;
    height: 150px;
}

.inner img {
    width: auto;
    max-width: 100%;
    max-height: 150px;
    height: auto;
}
<div class="outer">
  <div class="inner">
    <img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQwI_CFh8BfnYAn6pL7Pe1AX_LuxrvEs4HqL2qWNPoTvESUwj5hdw">
  </div>
</div>

在这个例子中 - 我希望它看起来像这样:

https://i.stack.imgur.com/a7nPt.png

css可以吗?

提前致谢

【问题讨论】:

    标签: css image resize center vertical-alignment


    【解决方案1】:

    只需在图片中添加以下内容

     margin: 0 auto;
        display: block;
    

    完整代码:

    .outer {
        position: relative;
        background: gray;
        width: 200px;
        height: 150px;
    }
    
    .inner {
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        background: gold;
        overflow: hidden;
        width: 200px;
        height: 150px;
    }
    
    .inner img {
        width: auto;
        max-width: 100%;
        max-height: 150px;
        height: auto;
        margin: 0 auto;
        display: block;
    }
    <div class="outer">
      <div class="inner">
        <img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQwI_CFh8BfnYAn6pL7Pe1AX_LuxrvEs4HqL2qWNPoTvESUwj5hdw"
      </div>
    </div>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-24
      • 2012-11-15
      • 2019-10-05
      • 1970-01-01
      • 2020-05-12
      相关资源
      最近更新 更多