【问题标题】: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 中采取了以下技巧,将imga 标记中垂直居中。

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

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

【问题讨论】:

    标签: html css center margin


    【解决方案1】:

    图像宽度不是 100%,因此 margin: 0 auto; 无法使图像居中对齐。最好的办法是在 ID 为 left-control&lt;a&gt; 标签上添加 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

        【讨论】:

          猜你喜欢
          • 2017-11-29
          • 2010-11-01
          • 2012-01-27
          • 2016-06-19
          • 2018-06-08
          • 1970-01-01
          • 2015-10-24
          • 2011-06-24
          • 2011-03-11
          相关资源
          最近更新 更多