在<a>, why is margin:0 auto; NOT working?

时间:2016-01-01 05:57:44

标签: html css css3 center margin

JSFiddle here.

内水平居中图像

OR

&#13;
&#13;
#left-control {
   float: left;
   height: 300px;
   width:300px;
   background-color:crimson;
}

#left-control:before {
    content: "";
    display: inline-block;
    vertical-align: middle;
    height: 100%;
}

#left-control img {
    vertical-align: middle;
    z-index: 1;
	
	margin: 0 auto;
}
&#13;
<a id="left-control">
    <img src="https://events.columbia.edu/3.10/calrsrc.MainCampus/themes/columbiaTheme/resourcesColumbia/FacebookIcon.png" />
 </a>
&#13;
&#13;
&#13;

我从here采取了以下攻击,将img标记中的a垂直居中。

问题是我习惯使用margin:0 auto;来固定内容。但问题在于它不能与垂直居中的这种技术一起工作。

为什么?我该怎么做才能解决这个问题?

3 个答案:

答案 0 :(得分:2)

使用以下css:

#left-control::before {
    height: 100%;
    content: "";
}
#left-control {
    background-color: crimson;
    display: table;
    height: 300px;
    line-height: 300px;
    text-align: center;
    width: 300px;
}

float: left;移除#left-control。并使用display: table; line-height: 300px; text-align: center;

display: inline-block;

中删除vertical-align: middle; #left-control::before

<强> Working Fiddle

答案 1 :(得分:1)

图像宽度不是100%,因此margin: 0 auto;无法使图像居中对齐。最好的办法是在ID text-align: center;的{​​{1}}代码上进行<a>,使图标居中对齐。

答案 2 :(得分:1)

添加文字对齐#left-control text-align:center

#left-control {
   float: left;
   height: 300px;
   width:300px;
text-align:center;
   background-color:crimson;
}

#left-control:before {
    content: "";
    display: inline-block;
    vertical-align: middle;
    height: 100%;
}

#left-control img {
    vertical-align: middle;
    z-index: 1;
	
	margin: 0 auto;
}
<a id="left-control">
    <img src="https://events.columbia.edu/3.10/calrsrc.MainCampus/themes/columbiaTheme/resourcesColumbia/FacebookIcon.png" />
 </a>