考虑以下HTML / CSS:
.container {
width: 100%;
height: 200px;
overflow: hidden;
}
.container img {
max-width: 100%;
height: auto;
}
<div class="container">
<img src="http://www.wallpapereast.com/static/images/HD-Wallpapers1_Q75eDHE.jpeg" alt="img" />
</div>
有没有办法可以将图像垂直居中放在容器中?
答案 0 :(得分:2)
.container {
width: 100%;
height: 200px;
overflow: hidden;
object-fit: cover;
}
.container img {
max-width: 100%;
height: auto;
position: relative;
top: 50%;
left: 0;
transform: translate(0, -50%);
}
<div class="container">
<img src="http://www.wallpapereast.com/static/images/HD-Wallpapers1_Q75eDHE.jpeg" alt="img" />
</div>
答案 1 :(得分:0)
你的图像比你的容器大......这是正常的吗?
我建议你在这种情况下使用背景图片......(背景位置:中心和背景尺寸:封面)
答案 2 :(得分:0)
更改css
CSS
div.horizontal {
display: flex;
justify-content: center;
}
div.vertical {
display: flex;
flex-direction: column;
justify-content: center;
}
.container {
width: 100%;
height: 200px;
overflow: hidden;
object-fit: cover;
}
.container img {
max-width: 100%;
height: auto;
}
HTML
<div class="horizontal container div1">
<div class="vertical">
<img src="http://www.wallpapereast.com/static/images/HD-Wallpapers1_Q75eDHE.jpeg" alt="img" />
</div>
</div>