css - 在 div 中居中图像 + 调整大小并保持图像比例

标签 css image resize center vertical-alignment

我试图将图像在 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>

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

/image/a7nPt.png

用css可以吗?

提前致谢

最佳答案

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

 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>

关于css - 在 div 中居中图像 + 调整大小并保持图像比例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51290162/

相关文章:

css - 如何将线性渐变应用于输入边框?

c++ - 使用 cv_image 实现 dlib pyramid_up

android - 如何在 android 中调整图像大小以在扩展通知中使用它?

c++ - GDI+图像缩放问题

Silverlight 4.0 - 使用鼠标事件裁剪图像

java - GWT:SplitLayoutPanel UiBinder

python - winfo_width() 即使在使用 pack() 之后也返回 1

Javascript/jQuery - 检测浏览器高度 - 简单修复?

javascript - 如何在将 <li> 附加到 <li> 组中时滚动 <li>

CSS/IE 7 问题