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

后端 未结 7 1684
野性不改
野性不改 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 22:56

    The CSS property top works exactly as left. It pushes the div from that direction. When you write top:50%, the div will be pushed down 50% from the top. You want it to be centered vertically, so you need to counter this by pulling it back up. This can be done using margin-top: -300px just like you used margin-left: -600px to pull it left.

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

提交回复
热议问题