Why is is top:50% in css not working?

后端 未结 7 1682
野性不改
野性不改 2021-02-03 22:30

I am making a website and I\'m trying to vertically center:

 position: absolute;
 width:1200px;
 height:600px;
 top: 50%;
 left: 50%;
 margin-left: -600px;
         


        
7条回答
  •  遥遥无期
    2021-02-03 23:03

    I'd like to take this opportunity to blatantly self-promote my answer to another question here on SO :)

    That being said, css "top" property gets correctly calculated based on the container element's height - effectively rendering the target element below the midline. What this means is the element needs to be pushed half-way up as explained in the linked question.

    Unfortunately such a seemingly straightforward task cannot be accomplished by adjusting top margin etc. without using absolute pixel-based values (+1 for Kristian Antonsen's answer) - one would imagine setting margin-top to "-50%" would mean just that, but according to css spec, margin values even on the vertical axis are calculated as a percentage always relative to the width of the containing block

提交回复
热议问题