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

后端 未结 7 1678
野性不改
野性不改 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:55

    I believe this may somewhat mimic the answer Kristian gave, but here's my two cents, which includes using percentages and also demonstrates one inside another:

    #parent {
        position: absolute;
        top: 50%;
        left: 50%;
        width: 120px;
        height: 60px;
        margin: -60px 0 0 -30px;
        background: blue;
    }
    #center {
        position: absolute;
        width: 50%;
        height: 50%;
        top: 50%;
        left: 50%;
        margin: -12.5% 0 0 -25%;
        background: green;
    }
    

    http://jsfiddle.net/userdude/MYD27/

    EDIT

    Looking at it further, I think you might run into issues if you're trying to do this with an element not container within a positioned element. For instance:

    Full View | Code View

    I don't think works the way you intended. When I add position: relative (or alternatively position: absolute), it does work I think as you intended:

    Full View | Code View

提交回复
热议问题