【问题标题】:vertically center images without float:none没有浮动的垂直居中图像:无
【发布时间】:2014-12-27 17:35:52
【问题描述】:

我发现了一些这样的问题,但我找不到答案:是否可以在每个 col-xs-1 引导单元中垂直居中图像,但不要用 float:none 杀死流体网格系统? jsfiddle project

HTML:

<div class="container">
<div class="row row-table">
  <div class="col-xs-1 col-xs-1-table-cell">
  </div>
  <div class="col-xs-1 col-xs-1-table-cell">
    <img src="http://placehold.it/50x50/" width="50" height="50"/>
  </div>
  <div class="col-xs-1 col-xs-1-table-cell">
    <img src="http://placehold.it/100x100/" width="100" height="100"/>
  </div>
</div>

css:

div.row {
border: solid 1px blue;
}
 .row-table {
display: table;
width: 100%;
}
 div.col-xs-1 {
 width:150px !important;
 height:160px !important;
 border: solid 1px yellow;
}
.col-xs-1-table-cell {
display: table-cell;
text-align: center;
vertical-align: middle;
//    float:none;
}

请取消注释 float:none;在 css 部分中,图像将居中,但单元格的流畅布局将被破坏(您可以更改浏览器窗口大小以尝试)

【问题讨论】:

  • 您有两个答案,请确保检查它们并标记您使用的答案是否正确

标签: html css twitter-bootstrap-3 vertical-alignment


【解决方案1】:

您需要在包含的单元格上设置 line-height 才能使垂直对齐起作用。将其设置为与高度值相同,然后在 img 上应用 vertical-align: middle 即可。

JS Fiddle

CSS

div.col-xs-1 {
    width:150px !important;
    height:160px !important;
    border: solid 1px yellow;
    line-height: 160px;
}
.col-xs-1-table-cell {
   display: table-cell;
   text-align: center;
}

.col-xs-1-table-cell img {
   vertical-align: middle;
}

【讨论】:

    【解决方案2】:

    position: relative 添加到.col-xs-1 以允许绝对定位&lt;img&gt; 相对于.col-xs-1。使用http://css-tricks.com/centering-css-complete-guide/ 中的技术来定位&lt;img&gt; 像这样

    img {
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
    }
    

    【讨论】:

      猜你喜欢
      • 2011-04-08
      • 2021-01-04
      • 1970-01-01
      • 1970-01-01
      • 2014-02-14
      • 2014-08-23
      • 1970-01-01
      • 2012-06-04
      • 2010-12-30
      相关资源
      最近更新 更多