我有一个div 200x200px。我想在div的中间放置一个50 x 50 px的图像。

怎样才能做到呢?

我能够得到它的中心水平使用文本对齐:中心的div。但垂直对齐是问题..


当前回答

这对我很管用。将此添加到image css:

img
{
   display: block;
   margin: auto;
}

其他回答

在CSS中这样做:

img
{

  display:table-cell;
  vertical-align:middle;
  margin:auto;
}

在div中

style="text-align:center; line-height:200px"

另一种方法(此处未提及)是使用Flexbox。

只需在container div上设置以下规则:

display: flex;
justify-content: center; /* align horizontal */
align-items: center; /* align vertical */

小提琴

div { 宽度:200 px; 身高:200 px; 边框:1px纯绿色; 显示:flex; justify-content:中心; /*对齐水平*/ 对齐项目:中心; /*垂直对齐*/ } < div > < img src = " http://lorempixel.com/50/50/food " alt = " / > < / div >

要了解Flexbox的一些特性并获得最大限度的浏览器支持的语法,最好从flexyboxes开始

此外,现在的浏览器支持也相当不错:caniuse

对于显示:flex和align-items的跨浏览器兼容性,您可以使用以下命令:

display: -webkit-box;
display: -webkit-flex;
display: -moz-box;
display: -ms-flexbox;
display: flex;
-webkit-flex-align: center;
-ms-flex-align: center;
-webkit-align-items: center;
align-items: center;

我有这个问题在HTML5中使用CSS3和我的图像在DIV中居中…哦,是的,我不能忘记我必须增加高度来显示图像…有一段时间我不知道它在哪里,直到我做了这个。我不认为位置和显示是必要的。

background-image: url('../Images/01.png');    
background-repeat:no-repeat;
background-position:center;
position:relative;
display:block;
height:60px;

这是正确的:

display: block;
margin-left: auto;
margin-right: auto 

否则,如果上面只给你水平居中,试试这个:

.outerContainer {
   position: relative;
}

.innerContainer {
   width: 50px; //your image/element width here
   height: 50px; //your image/element height here
   overflow: auto;
   margin: auto;
   position: absolute;
   top: 0; left: 0; bottom: 0; right: 0;
}