与 css 垂直对齐时何时使用绝对位置与相对位置

When to use position absolute vs position relative when vertically aligning with css

最初我按照这篇文章在子元素上使用了position: relativehttp://zerosixthree.se/vertical-align-anything-with-just-3-lines-of-css/

http://codepen.io/anon/pen/KpWKWg

但我无法让它在我的代码中工作:

http://jsfiddle.net/ge77ma0e/


然后我发现这些在子元素上使用 position: absolute 的指令:https://css-tricks.com/centering-css-complete-guide/#vertical-block-unknown

http://codepen.io/chriscoyier/pen/lpema

当我在我的代码上尝试它时,它终于起作用了:

http://jsfiddle.net/y2ajtmks/

有什么好的解释吗?

您错过了 .valigndisplay: block;。 transform 元素看起来应该应用于块元素,而不是内联元素。这是文档:

CSS Transforms Module Level 1 - Terminology - Transformable Element

A transformable element is an element in one of these categories:

  • an element whose layout is governed by the CSS box model which is either a block-level or atomic inline-level element, or whose display property computes to table-row, table-row-group, table-header-group, table-footer-group, table-cell, or table-caption
  • an element in the SVG namespace and not governed by the CSS box model which has the attributes transform, ‘patternTransform‘ or gradientTransform.

此外,如果您只需要垂直居中(而不是水平居中),请将 transforms 更改为:

-webkit-transform: translateY(-50%);
-moz-transform: translateY(-50%);
-ms-transform: translateY(-50%);
transform: translateY(-50%);

默认情况下,DOM 上的所有元素都是 position:statictop, left, right, bottom 之类的属性不能用于静态定位的元素。使用任何其他定位上下文,如 relative absolutefixed 允许您使用这些值。

解决方案中使用的方法是将一个元素从顶部推入50%,然后将其向上拉出元素height的一半。这就是 transform 发挥作用的地方。

现在,您可以看到您的两篇文章都使用了 static 以外的不同定位上下文。首先,它使用 'relative',在 css-tricks 示例中,您会看到 absolute.

您的代码无法运行的原因是 transform 适用于块级元素,但您的文本位于 span 中。添加一个 display:block 就可以了。

我还注意到你有 transform: translate(-50%,-50%); 应该只是 translateY(-50%) 来补偿你试图垂直居中的任何盒子的高度,方法是通过 top 推动它 50%.