使用鬼元素'在其容器内垂直对齐宽度为100%的内联块元素

时间:2015-07-17 18:53:37

标签: css alignment vertical-alignment

this article提到了一种使用“鬼元素”在css中垂直居中元素的技巧。

/* This parent can be any width and height */
.block {
  text-align: center;

  /* May want to do this if there is risk the container may be narrower than the element inside */
  white-space: nowrap;
}

/* The ghost, nudged to maintain perfect centering */
.block:before {
  content: '';
  display: inline-block;
  height: 100%;
  vertical-align: middle;
  margin-right: -0.25em; /* Adjusts for spacing */
}

/* The element to be centered, can also be of any width and height */ 
.centered {
  display: inline-block;
  vertical-align: middle;
  width: 300px;
}

codepen here.

但是,当要居中的元素具有width:100%时,它不起作用,因为元素被推到一个新行上。您是如何调整解决方案以便在这种情况下工作的?我需要一个具有良好浏览器支持的解决方案,包括IE9 +

1 个答案:

答案 0 :(得分:0)

我弄清楚了,我正在遭遇“空内联块元素问题之间的间隔”。有几种方法可以解决这个问题,我通过注释掉HTML中元素之间的空白来修复它。 Here is a working plunker