How to center a div vertically?

后端 未结 4 500
忘掉有多难
忘掉有多难 2021-01-01 19:54

I have a div that I want to center horizontally and vertically.

For the horizontal issue everything is great, but I have a problem with the vertical ali

4条回答
  •  春和景丽
    2021-01-01 20:47

    If you only have to support browsers that support transform (or its vendor prefixed versions), use this one weird old trick to vertically align elements.

    #child {
        position: relative;
        top: 50%;
        transform: translateY(-50%);
    }
    

    If you have to support older browsers, you can use a combination of these, but they can be a pain due to the differences in rendering block vs table.

    #parent {
        display: table;
    }
    
    #child {
         display: table-cell;
         vertical-align: middle;
    }
    

    If your height is fixed and you need to support those really old, pesky browsers...

    #parent {
       position: relative;
    }
    
    #child {
       height: 100px;
       position: absolute;
       top: 50%;
       margin-top: -50px;
    }
    

    If your height is not fixed, there is a workaround.

    See it on jsFiddle.

提交回复
热议问题