我试图将图像在 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>
在这个例子中——我希望它看起来像这样:
用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/