当图像高于容器时,将图像垂直居中 [英] Vertically center image when image is higher than container
问题描述
我的响应式设计带有放置在容器中的标头图像.图像具有width:100%;
和height:auto;
,因此当您放大视口时图像会增大.我不想超过某个高度,因此容器具有max-height
.图像仍然会增长,但是现在底部被切除了,因为它与容器的顶部对齐.
I have a responsive design with a header image which is placed in a container. The image has width:100%;
and height:auto;
so it grows as you enlarge the viewport. I don't want to exceed a certain height so the container has a max-height
. The image still grows but now the bottom part is cut off now because it aligns to the top of the container.
我希望图像在容器中保持垂直居中,以便图像的顶部和底部被切除.结果应如下所示:
I would like the image to stay vertically centered in it's container so that parts of the image are cut off at the top and at the bottom. The outcome should look like this:
标题图片是由用户上传的,因此它们的高度可能不同,因此我无法使用特定的像素值.是否有CSS解决方案,或者我必须使用JavaScript?
The header images are uploaded by users so they might have different heights therefore I cannot work with specific pixel-values. Is there a CSS-solution for this or do I have to use JavaScript?
这是代码:
.wrapper {
width: 90%;
max-width: 600px;
margin: 1em auto;
background-color: #E9ADAD;
}
.container {
text-align: center;
height: auto;
line-height: 200px;
max-height: 200px;
overflow: hidden;
}
img {
width: 100%;
height: auto !important;
vertical-align: middle;
}
<div class="wrapper">
<div class="container">
<img src="http://placehold.it/600x300/C00000/FFFFFF&text=Image+vertically+centered">
</div>
</div>
然后我准备了小提琴.
推荐答案
您可以对图像使用绝对定位,负的上下值和margin:auto;
将图像在容器中垂直居中:
You can use absolute positioning for your image , negative top/bottom values and margin:auto;
to verticaly center the image in the container :
.wrapper {
width: 90%;
max-width: 600px;
margin: 1em auto;
background-color: #E9ADAD;
max-height: 200px;
}
.container {
position:relative;
padding-bottom:40%;
overflow: hidden;
}
img {
position:absolute;
top:-50%; bottom:-50%;
margin:auto;
width: 100%;
height: auto;
}
<div class="wrapper">
<div class="container">
<img src="http://placehold.it/600x300/C00000/FFFFFF&text=Image+vertically+centered">
</div>
</div>
这篇关于当图像高于容器时,将图像垂直居中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!