【问题标题】:Use 'ghost element' to vertically align an inline-block element of width 100% within its container使用 'ghost element' 在其容器内垂直对齐宽度为 100% 的 inline-block 元素
【发布时间】:2015-10-07 14:04:22
【问题描述】:

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+

【问题讨论】:

  • 我特别需要这个解决方案是有原因的。另外,我相信您在链接中提出的“未知高度和宽度的元素的水平和垂直方向”的解决方案是不理想的,因为它can cause elements to become blurred due to sub-pixel rendering
  • 秋千和环形交叉路口...您付钱,您可以选择。祝你好运。
  • 您是在使用 :before 而不是 ::before,还是只是问题中的拼写错误?
  • 啊!我正在这样做,但即使你只使用一个冒号也可以。

标签: css alignment vertical-alignment


【解决方案1】:

我想通了,我遇到了“空内联块元素之间的间距问题”。有几种方法可以解决这个问题,我通过注释掉 HTML 中元素之间的空格来修复它。 Here is a working plunker

【讨论】:

    猜你喜欢
    • 2023-03-09
    • 2012-10-08
    • 1970-01-01
    • 2014-12-01
    • 1970-01-01
    • 2014-10-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多