我正在尝试将图像垂直放置在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是否可能?
预先感谢
答案 0 :(得分: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>