css - 使用 'ghost element' 在其容器内垂直对齐宽度为 100% 的内联 block 元素

标签 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+

最佳答案

我想通了,我正在遭受“空内联 block 元素之间的间距问题”的困扰。有几种方法可以解决这个问题,我通过注释掉 HTML 中元素之间的空格来解决这个问题。 Here is a working plunker

关于css - 使用 'ghost element' 在其容器内垂直对齐宽度为 100% 的内联 block 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31482795/

相关文章:

css - 在填充空间的同时在 anchor 中垂直居中文本

css - 垂直居中段落

css - 使最后一个内联列表项扩展容器的剩余宽度

html - 使用 bootstrap 3 将内容居中

html - 如何在 LI 中垂直居中文本和图像

html - 在左侧对齐文本,但也在我的 div 的中心

delphi - 如何动态创建与顶部对齐但在其他对齐控件之后的控件?

html - 如何在不创建两条单独的行的情况下将 h3 与 p 对齐?

html - 图像的 Bootstrap 进度条中心并删除进度条上方的灰色

html - 有什么方法可以将一些样式繁多的 HTML 与网站的其余样式隔离开来?