何时使用位置绝对vs位置相对时垂直对齐css [英] When to use position absolute vs position relative when vertically aligning with css
问题描述
最初我遵循这个在子元素上使用 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
当我在我的代码上尝试时,它终于工作了:
$ b $
display:block; / code>在 .valign
。变换元素似乎应该应用于块元素,而不是内联。以下是文档:
是以下类别之一的元素:
- 一个元素,其布局由CSS框模型控制, http://www.w3.org/TR/CSS2/visuren.html#block-level =nofollow>块级或 atomic inline-level element ,或者其显示属性计算到table-row,table-row-group,table-header-group,table-footer-group,table-cell或table- caption
- 在SVG命名空间中的一个元素,并且不受具有transform,'patternTransform'或gradientTransform属性的CSS框模型的管理。
此外,如果您只需要垂直居中(而不是水平居中),请更改 transform
到:
-webkit-transform:translateY(-50%);
-moz-transform:translateY(-50%);
-ms-transform:translateY(-50%);
transform:translateY(-50%);
Originally I followed this article which used position: relative
on the child element: http://zerosixthree.se/vertical-align-anything-with-just-3-lines-of-css/
http://codepen.io/anon/pen/KpWKWg
But I couldn't get it to work on my code for the life of me:
Then I found these instructions which use position: absolute
on the child element: https://css-tricks.com/centering-css-complete-guide/#vertical-block-unknown
http://codepen.io/chriscoyier/pen/lpema
And when I tried it on my code it finally worked:
Any good explanations?
解决方案 You miss display: block;
on .valign
. The transform element as it seems should be applied to a block element, not inline. Here is the documentation:
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.
Also if you need to center only verticaly (and not horizontaly), change you transform
s to:
-webkit-transform: translateY(-50%);
-moz-transform: translateY(-50%);
-ms-transform: translateY(-50%);
transform: translateY(-50%);
这篇关于何时使用位置绝对vs位置相对时垂直对齐css的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!