When to use position absolute vs position relative

2019-05-28 23:29发布

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:

http://jsfiddle.net/ge77ma0e/


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:

http://jsfiddle.net/y2ajtmks/

Any good explanations?

2条回答
姐就是有狂的资本
2楼-- · 2019-05-29 00:17

By default, all elements on DOM are position:static. Properties like top, left, right, bottom aren't usable with a statically positioned element. Using any other positioning context like relative absolute or fixed allow you to use these values.

The method used in the solution is to push an element from top by 50% and then pulling it upwards by half the height of the element. This is where transform comes into play.

Now, you can see that both of your articles use a different positioning context other than static. In first, it uses 'relative' and in the css-tricks example you see absolute.

The reason why your code isn't working because transform works on block-level elements but your text is inside a span. Add a display:block to it and you should be good to go.

I also noticed that you have transform: translate(-50%,-50%); which should just be translateY(-50%) to compensate for the height of any box you are trying to vertically center by pushing it from top by 50%.

查看更多
小情绪 Triste *
3楼-- · 2019-05-29 00:33

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 transforms to:

-webkit-transform: translateY(-50%);
-moz-transform: translateY(-50%);
-ms-transform: translateY(-50%);
transform: translateY(-50%);
查看更多
登录 后发表回答