在 div 内居中图像 + 调整大小并保持图像比例
Center image inside div + resize and keep proportion of image
我正在尝试将图像在 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可以吗?
提前致谢
只需在图像中添加以下内容
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>
我正在尝试将图像在 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可以吗?
提前致谢
只需在图像中添加以下内容
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>