【问题标题】:Horizontally centering image inside <a>, why is margin:0 auto; NOT working?<a> 内的水平居中图像,为什么 margin:0 auto;不工作?
【发布时间】:2016-04-05 20:48:59
【问题描述】:
JSFiddle here.
或
#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>
我从here 中采取了以下技巧,将img 在a 标记中垂直居中。
问题是我习惯于使用margin:0 auto; 来居中。但问题是它不能与这种垂直居中的技术一起使用。
这是为什么呢?我该怎么做才能解决这个问题?
【问题讨论】:
标签:
html
css
center
margin
【解决方案1】:
图像宽度不是 100%,因此 margin: 0 auto; 无法使图像居中对齐。最好的办法是在 ID 为 left-control 的 <a> 标签上添加 text-align: center; 以使图标居中对齐。
【解决方案2】:
添加文字对齐#left-controltext-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>
【解决方案3】:
使用以下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;
Working Fiddle