如何在div中包含图像的div中心? [英] How to center div that contains an image within a div?

查看:196
本文介绍了如何在div中包含图像的div中心?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将图片放置在div的垂直和水平方向。我正在使用display inline-block属性。

I need to center a image inside a div both vertically and horizontally. I am using the display inline-block property.

HTML

<div class="container">
   <div class="box">
     <div class="image-container"><img src="image.gif"></div>
   </div>
</div>

CSS

.box {
    display: inline-block;
    width: 32px;
    height: 32px;
    border: 1px solid #f2f2f2;
    margin-left: 1px;
    margin-top: 5px;
}


推荐答案

jsFiddle示例

基本上,我们使用 vertical-align:middle 进行垂直居中, c $ c> text-align:center 用于水平居中。为了 vertical-align:middle div 上工作,我们需要将父元素设置为 display:table ,目标孩子 div display:table-cell 。当然,你可以实现这样的中心与绝对定位,但是,这将要求你知道 img 的维度。此方法适用于未知维度。

Basically, we are using vertical-align:middle for vertical centering, and text-align:center for horizontal centering. 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. Sure you could achieve such centering with absolute positoning, however, that would require you to know the dimensions of the img. This approach works for unknown dimensions.

HTML

<div class="container">
   <div class="box">
       <img src="http://placehold.it/200x200">
   </div>
</div>

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;
}

这篇关于如何在div中包含图像的div中心?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆