水平居中图像内部<a>,为什么边距:0自动;不工作?



JSFiddle

#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;
}
<a id="left-control">
    <img src="https://events.columbia.edu/3.10/calrsrc.MainCampus/themes/columbiaTheme/resourcesColumbia/FacebookIcon.png" />
 </a>

从这里开始,我采用了以下技巧,将img垂直居中放置在a标签中。

问题是我习惯于使用margin:0 auto;来集中事物。但问题是,它不适用于这种垂直居中的技术。

为什么?我能做些什么来解决这个问题?

使用以下css:

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

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

并从#left-control::before 中删除display: inline-block; vertical-align: middle;

工作Fiddle

图像宽度不是100%,因此margin: 0 auto;无法对图像进行居中对齐。您最好在ID为left-control<a>标签上执行text-align: center;,以使图标居中对齐。

添加文本对齐#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>

最新更新