最初我按照这篇文章在子元素上使用了 position:relative
: http://zerosixthree.se/vertical-align-anything-with-just-3-lines-of-css/
http://codepen.io/anon/pen/KpWKWg
但我一生都无法让它在我的代码上工作:
然后我发现这些指令在子元素上使用 position:absolute
: https://css-tricks.com/centering-css-complete-guide/#vertical-block-unknown
http://codepen.io/chriscoyier/pen/lpema
当我在我的代码上尝试它时,它终于起作用了:
有什么好的解释吗?
最佳答案
您错过了 .valign
上的 display: block;
。变换元素看起来应该应用于 block 元素,而不是内联元素。这是文档:
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.
此外,如果您只需要垂直居中(而不是水平),请将 transform
更改为:
-webkit-transform: translateY(-50%);
-moz-transform: translateY(-50%);
-ms-transform: translateY(-50%);
transform: translateY(-50%);
关于html - 使用 css 垂直对齐时何时使用绝对位置与相对位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30587090/