[英]How to center div that contains an image within a div?
I need to center a image inside a div both vertically and horizontally. 我需要在div内垂直和水平居中。 I am using the display inline-block property.
我正在使用display inline-block属性。
HTML HTML
<div class="container">
<div class="box">
<div class="image-container"><img src="image.gif"></div>
</div>
</div>
CSS CSS
.box {
display: inline-block;
width: 32px;
height: 32px;
border: 1px solid #f2f2f2;
margin-left: 1px;
margin-top: 5px;
}
This approach works perfectly for dynamic content of unknown dimensions. 此方法适用于未知维度的动态内容。
Basically, we are using vertical-align:middle
for vertical centering, and text-align:center
for horizontal centering. 基本上,我们使用
vertical-align:middle
进行垂直居中,使用text-align:center
进行水平居中。 In order for vertical-align:middle
to work on a div
, we need to set the parent elements to display:table
, and the targeted child div
to display:table-cell
. 为了使
vertical-align:middle
能够在div
上工作,我们需要将父元素设置为display:table
,并将目标子div
为display:table-cell
。 Sure you could achieve such centering with absolute
positoning, however, that would require you to know the dimensions of the img
. 当然,你可以通过
absolute
定位实现这种定心,但这需要你知道img
的尺寸。 This approach works for unknown dimensions. 这种方法适用于未知的维度。
HTML HTML
<div class="container">
<div class="box">
<img src="http://placehold.it/200x200">
</div>
</div>
CSS CSS
html, body {
height:100%;
width:100%;
margin:0px;
}
.container {
display:table;
vertical-align:middle;
text-align:center;
height:100%;
width:100%;
}
.box {
display:table-cell;
vertical-align:middle;
}
for the horizantal you can use: 对于你可以使用的horizantal:
.box {
display: inline-block;
width: 32px;
height: 32px;
border: 1px solid #f2f2f2;
margin:auto;
text-align:center;
}
for the vertical as far as i know you can use 对于垂直,据我所知你可以使用
#content {position:absolute; top:50%; height:240px; margin-top:-120px; /* negative half of the height */}
please read: http://blog.themeforest.net/tutorials/vertical-centering-with-css/ 请阅读: http : //blog.themeforest.net/tutorials/vertical-centering-with-css/
You can put the image into a table like this: 您可以将图像放入如下表格中:
<table class="container">
<tr class="box">
<td class="image-container"><img src="image.gif"></td>
</tr>
</table>
And then use this in your CSS: 然后在CSS中使用它:
.image-container {
vertical-align: middle;
text-align: center;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.