Html 垂直对齐具有响应高度的 div 内的图像
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18516317/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Vertically align an image inside a div with responsive height
提问by user1794295
I have the following code which sets up a container which has a height that changes with the width when the browser is re-sized (to maintain a square aspect ratio).
我有以下代码,它设置了一个容器,当浏览器重新调整大小(以保持方形纵横比)时,该容器的高度会随着宽度而变化。
HTML
HTML
<div class="responsive-container">
<div class="dummy"></div>
<div class="img-container">
<IMG HERE>
</div>
</div>
CSS
CSS
.responsive-container {
position: relative;
width: 100%;
border: 1px solid black;
}
.dummy {
padding-top: 100%; /* forces 1:1 aspect ratio */
}
.img-container {
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
}
How can I vertically align the IMG inside the container? All my images have variable heights and the container can't have a fixed height/line height because it's responsive... Please help!
如何垂直对齐容器内的 IMG?我所有的图像都有可变的高度,容器不能有固定的高度/行高,因为它是响应式的......请帮忙!
回答by Hashem Qolami
Here is a technique to align inline elements inside a parent, horizontally and vertically at the same time:
这是一种在parent中同时水平和垂直对齐内联元素的技术:
Vertical Alignment
垂直对齐
1)In this approach, we create an inline-block(pseudo-)element as the first (or last) child of the parent, and set its heightproperty to 100%to take all the height of its parent.
1)在这种方法中,我们创建一个inline-block(伪)元素作为parent的第一个(或最后一个)子元素,并将其height属性设置100%为采用其parent 的所有高度。
2)Also, adding vertical-align: middlekeeps the inline(-block) elements at the middle of the line space. So, we add that CSS declaration to the first-childand our element(the image) both.
2)此外,添加vertical-align: middle将 inline(-block) 元素保持在行空间的中间。因此,我们将该 CSS 声明添加到第一个子元素和我们的元素(图像)。
3)Finally, in order to remove the white space character between inline(-block)elements, we could set the font size of the parentto zero by font-size: 0;.
3)最后,为了去除inline(-block)元素之间的空白字符,我们可以将父元素的字体大小设置为零font-size: 0;。
Note:I used Nicolas Gallagher's image replacement techniquein the following.
注意:我在下面使用了 Nicolas Gallagher 的图像替换技术。
What are the benefits?
有什么好处?
- The container (parent) can have dynamic dimensions.
There's no need to specify the dimensions of the image element explicitly.
We can easily use this approach to align a
<div>element verticallyas well; which may have a dynamic content (height and/or width). But note that you have to re-set thefont-sizeproperty of thedivto display the inside text. Online Demo.
- 容器(parent)可以具有动态维度。
无需明确指定图像元素的尺寸。
我们也可以轻松地使用这种方法来垂直对齐
<div>元素;它可能具有动态内容(高度和/或宽度)。但请注意,您必须重新设置 的font-size属性div才能显示内部文本。在线演示。
<div class="container">
<div id="element"> ... </div>
</div>
.container {
height: 300px;
text-align: center; /* align the inline(-block) elements horizontally */
font: 0/0 a; /* remove the gap between inline(-block) elements */
}
.container:before { /* create a full-height inline block pseudo=element */
content: ' ';
display: inline-block;
vertical-align: middle; /* vertical alignment of the inline element */
height: 100%;
}
#element {
display: inline-block;
vertical-align: middle; /* vertical alignment of the inline element */
font: 16px/1 Arial sans-serif; /* <-- reset the font property */
}
The output
输出


Responsive Container
响应式容器
This section is not going to answer the question as the OP already knows how to create a responsive container. However, I'll explain how it works.
本节不会回答这个问题,因为 OP 已经知道如何创建响应式容器。但是,我将解释它是如何工作的。
In order to make the heightof a container element changes with its width(respecting the aspect ratio), we could use a percentage value for top/bottom paddingproperty.
为了使容器元素的高度随其宽度而变化(考虑纵横比),我们可以为 top/bottompadding属性使用百分比值。
A percentage valueon top/bottom padding or margins is relative to the width of the containing block.
顶部/底部填充或边距的百分比值相对于包含块的宽度。
For instance:
例如:
.responsive-container {
width: 60%;
padding-top: 60%; /* 1:1 Height is the same as the width */
padding-top: 100%; /* width:height = 60:100 or 3:5 */
padding-top: 45%; /* = 60% * 3/4 , width:height = 4:3 */
padding-top: 33.75%; /* = 60% * 9/16, width:height = 16:9 */
}
Here is the Online Demo. Comment out the lines from the bottom and resize the panel to see the effect.
这是在线演示。注释掉底部的线条并调整面板大小以查看效果。
Also, we could apply the paddingproperty to a dummychild or :before/:afterpseudo-element to achieve the same result. But notethat in this case, the percentage value on paddingis relative to the widthof the .responsive-containeritself.
此外,我们可以将该padding属性应用于虚拟子元素或:before/:after伪元素以获得相同的结果。但请注意,在这种情况下,百分比值padding是相对于自身宽度的.responsive-container。
<div class="responsive-container">
<div class="dummy"></div>
</div>
.responsive-container { width: 60%; }
.responsive-container .dummy {
padding-top: 100%; /* 1:1 square */
padding-top: 75%; /* w:h = 4:3 */
padding-top: 56.25%; /* w:h = 16:9 */
}
Demo #1.
Demo #2(Using :afterpseudo-element)
Adding the content
添加内容
Using padding-topproperty causes a huge spaceat the top or bottom of the content, inside the container.
使用padding-top属性会在容器内部的内容顶部或底部产生巨大的空间。
In order to fix that, we have wrap the content by a wrapper element, remove that element from document normal flow by using absolute positioning, and finally expand the wrapper (bu using top, right, bottomand leftproperties) to fill the entire space of its parent, the container.
为了解决这个问题,就需要通过一个包装元件包的内容,通过利用来自原稿正常流中删除该元素绝对定位,最后展开的包装(BU使用top,right,bottom和left属性)来填充它的父的整个空间,该容器。
Here we go:
开始了:
.responsive-container {
width: 60%;
position: relative;
}
.responsive-container .wrapper {
position: absolute;
top: 0; right: 0; bottom: 0; left: 0;
}
Here is the Online Demo.
这是在线演示。
Getting all together
聚在一起
<div class="responsive-container">
<div class="dummy"></div>
<div class="img-container">
<img src="http://placehold.it/150x150" alt="">
</div>
</div>
.img-container {
text-align:center; /* Align center inline elements */
font: 0/0 a; /* Hide the characters like spaces */
}
.img-container:before {
content: ' ';
display: inline-block;
vertical-align: middle;
height: 100%;
}
.img-container img {
vertical-align: middle;
display: inline-block;
}
Here is the WORKING DEMO.
这是工作演示。
Obviously, you could avoid using ::beforepseudo-element for browser compatibility, and create an element as the first child of the .img-container:
显然,::before为了浏览器兼容性,您可以避免使用伪元素,并创建一个元素作为 的第一个子元素.img-container:
<div class="img-container">
<div class="centerer"></div>
<img src="http://placehold.it/150x150" alt="">
</div>
.img-container .centerer {
display: inline-block;
vertical-align: middle;
height: 100%;
}
Using max-*properties
使用max-*属性
In order to keep the image inside of the box in lower width, you could set max-heightand max-widthproperty on the image:
为了使框内的图像保持较低的宽度,您可以在图像上设置max-height和max-width属性:
.img-container img {
vertical-align: middle;
display: inline-block;
max-height: 100%; /* <-- Set maximum height to 100% of its parent */
max-width: 100%; /* <-- Set maximum width to 100% of its parent */
}
Here is the UPDATED DEMO.
这是更新的演示。
回答by Danield
With flexbox this is easy:
使用 flexbox 这很容易:
Just add the following to the image container:
只需将以下内容添加到图像容器中:
.img-container {
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
display: flex; /* add */
justify-content: center; /* add to align horizontal */
align-items: center; /* add to align vertical */
}
回答by Tibos
Use this css, as you already have the markup for it:
使用这个 css,因为你已经有了它的标记:
.img-container {
position: absolute;
top: 50%;
left: 50%;
}
.img-container > img {
margin-top:-50%;
margin-left:-50%;
}
Here is a working JsBin: http://jsbin.com/ihilUnI/1/edit
这是一个有效的 JsBin:http://jsbin.com/ihilUnI/1/edit
This solution only works for square images (because a percentage margin-top value depends on the width of the container, not the height). For random-size images, you can do the following:
此解决方案仅适用于方形图像(因为百分比 margin-top 值取决于容器的宽度,而不是高度)。对于随机大小的图像,您可以执行以下操作:
.img-container {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%); /* add browser-prefixes */
}
Working JsBin solution: http://jsbin.com/ihilUnI/2/edit
工作 JsBin 解决方案:http://jsbin.com/ihilUnI/2/edit
回答by Salman A
You can center an image, both horizontally and vertically, using margin: autoand absolute positioning. Also:
您可以使用margin: auto绝对定位将图像水平和垂直居中。还:
- It is possible to ditch extra markup by using pseudo elements.
- It is possible to display the middle portion of LARGE images by using negative left, top, right and bottom values.
- 可以通过使用伪元素来丢弃额外的标记。
- 可以使用负的左、上、右和下值来显示 LARGE 图像的中间部分。
.responsive-container {
margin: 1em auto;
min-width: 200px; /* cap container min width */
max-width: 500px; /* cap container max width */
position: relative;
overflow: hidden; /* crop if image is larger than container */
background-color: #CCC;
}
.responsive-container:before {
content: ""; /* using pseudo element for 1:1 ratio */
display: block;
padding-top: 100%;
}
.responsive-container img {
position: absolute;
top: -999px; /* use sufficiently large number */
bottom: -999px;
left: -999px;
right: -999px;
margin: auto; /* center horizontally and vertically */
}
<p>Note: images are center-cropped on <400px screen width.
<br>Open full page demo and resize browser.</p>
<div class="responsive-container">
<img src="http://lorempixel.com/400/400/sports/9/">
</div>
<div class="responsive-container">
<img src="http://lorempixel.com/400/200/sports/8/">
</div>
<div class="responsive-container">
<img src="http://lorempixel.com/200/400/sports/7/">
</div>
<div class="responsive-container">
<img src="http://lorempixel.com/200/200/sports/6/">
</div>
回答by Salman A
Try this one
试试这个
.responsive-container{
display:table;
}
.img-container{
display:table-cell;
vertical-align: middle;
}
回答by John Slegers
Here's a technique that allows you to center ANY content both vertically and horizontally!
这是一种允许您将任何内容垂直和水平居中的技术!
Basically, you just need a two containers and make sure your elements meet the following criteria.
基本上,您只需要两个容器并确保您的元素满足以下标准。
The outher container :
外部容器:
- should have
display: table;
- 应该有
display: table;
The inner container :
内部容器:
- should have
display: table-cell; - should have
vertical-align: middle; - should have
text-align: center;
- 应该有
display: table-cell; - 应该有
vertical-align: middle; - 应该有
text-align: center;
The content box :
内容框:
- should have
display: inline-block;
- 应该有
display: inline-block;
If you use this technique, just add your image (along with any other content you want to go with it) to the content box.
如果您使用此技术,只需将您的图像(以及您想要使用的任何其他内容)添加到内容框中。
Demo :
演示:
body {
margin : 0;
}
.outer-container {
position : absolute;
display: table;
width: 100%;
height: 100%;
background: #ccc;
}
.inner-container {
display: table-cell;
vertical-align: middle;
text-align: center;
}
.centered-content {
display: inline-block;
background: #fff;
padding : 12px;
border : 1px solid #000;
}
img {
max-width : 120px;
}
<div class="outer-container">
<div class="inner-container">
<div class="centered-content">
<img src="https://i.stack.imgur.com/mRsBv.png" />
</div>
</div>
</div>
See also this Fiddle!
另见这个小提琴!
回答by Alexandra
I came across this thread in search of a solution that:
我遇到了这个线程以寻找解决方案:
- uses 100% of the given image's width
- keeps the image aspect ratio
- keeps the image vertically aligned to the middle
- works in browsers that do not fully support flex
- 使用给定图像宽度的 100%
- 保持图像纵横比
- 保持图像垂直居中对齐
- 适用于不完全支持 flex 的浏览器
Testing someof the solutions posted above I didn't find one to meet all of this criteria, so I put together this simple one which might be useful for other people needing to do the same:
测试上面发布的一些解决方案,我没有找到满足所有这些标准的解决方案,所以我把这个简单的解决方案放在一起,它可能对其他需要做同样的人有用:
.container {
width: 30%;
float: left;
border: 1px solid turquoise;
margin-right: 3px;
margin-top: 3px;
}
.container:last-of-kind {
margin-right: 0px;
}
.image-container {
position: relative;
overflow: hidden;
padding-bottom: 70%;
/* this is the desired aspect ratio */
width: 100%;
}
.image-container img {
position: absolute;
/* the following 3 properties center the image on the vertical axis */
top: 0;
bottom: 0;
margin: auto;
/* uses image at 100% width (also meaning it's horizontally center) */
width: 100%;
}
<div class="container">
<div class="image-container">
<img src="http://placehold.it/800x800" class="img-responsive">
</div>
</div>
<div class="container">
<div class="image-container">
<img src="http://placehold.it/800x800" class="img-responsive">
</div>
</div>
<div class="container">
<div class="image-container">
<img src="http://placehold.it/800x800" class="img-responsive">
</div>
</div>
Working example on JSFiddle
JSFiddle 上的工作示例
回答by William
html code
html代码
<div class="image-container">
<img src=""/>
</div>
<div class="image-container">
<img src=""/>
</div>
css code
css代码
img
{
position: relative;
top: 50%;
transform: translateY(-50%);
}
回答by Discover
Make another div and add both 'dummy' and 'img-container' inside the div
制作另一个 div 并在 div 中添加 'dummy' 和 'img-container'
Do HTML and CSS like follows
像下面这样做 HTML 和 CSS
html , body {height:100%;}
.responsive-container { height:100%; display:table; text-align:center; width:100%;}
.inner-container {display:table-cell; vertical-align:middle;}
<div class="responsive-container">
<div class="inner-container">
<div class="dummy">Sample</div>
<div class="img-container">
Image tag
</div>
</div>
</div>
Instead of 100% for the 'responsive-container' you can give the height that you want.,
你可以给你想要的高度,而不是 100% 的“响应容器”。
回答by Paramasivan
Try
尝试
Html
html
<div class="responsive-container">
<div class="img-container">
<IMG HERE>
</div>
</div>
CSS
CSS
.img-container {
position: absolute;
top: 0;
left: 0;
height:0;
padding-bottom:100%;
}
.img-container img {
width:100%;
}

