Five best schemes for horizontal and vertical centering of CSS

CSS align Center

  • The browser prefix is omitted in the code
  • The following examples are sorted by my personal criteria
  • Of course, there are more ways to deal with the middle, but I think only these five ways are the most perfect solutions

flex Center

Advantage: the unknown height can be centered

<style>
    .wrap{height: 100%;display: flex; justify-content: center; align-items: center;align-content:center;}
    
    .other{background-color: #ccc; width: 400px;height: 400px;} / * additional styles can be removed*/
</style>

<div class="wrap">

    <div class="other">
        <h2>This is the second level content will not be centered</h2>
    </div>

</div>

position + translate centered

Advantages: it can center the unknown height with the least nesting

<style>
    /* position Optional absolute|fixed*/
    .center{position: absolute;left: 50%;top: 50%; transform: translate(-50%,-50%);}
    
    .other{background-color: #ccc;} / * extra styles can be removed*/
</style>

<div class="center other">
    <h2>The content of this layer will not be centered</h2>
</div>

Table cell center

Disadvantages: 1. The width (. center) of the middle layer needs to be set. 2. Nesting one more layer (. Cell) in the outer layer 3. The width of the middle layer must be set (allowed%)

<style>
    .wrap{display: table;width: 100%;height: 100%;}
    .cell{display: table-cell;vertical-align:middle;}
    .center{width: 400px;margin-left:auto;margin-right:auto;}
    
    .other{background-color: #CCC; height: 400px;} / * additional styles can be removed*/
</style>

<div class="wrap">
    <div class="cell">

        <div class="center other">
            <h2>The content of this layer will not be centered</h2>
        </div>

    </div>
</div>

Traditional center (2 kinds)

Disadvantages: 1. The margin value must be auto. 2. The height and width of the middle layer must be set (allowed%) 3. position must be used

<style>
    /*
        1. left,top,right,bottom Can be any, but must be equal
        2. position Optional absolute|fixed
    */
    .center{position: absolute;left: 10px;top: 10px;right: 10px;bottom: 10px;margin: auto;width: 400px;height: 400px;}

    .other{background-color: #ccc;} / * extra styles can be removed*/
</style>

<div class="center other">
    <h2>The content of this layer will not be centered</h2>
</div>

Disadvantages: the middle layer must be set with fixed height and width, and the mapping needs to be calculated by height and width.

<style>
    .wrap{position: relative;height: 100%;}
    .center{position: absolute;left: 50%;top: 50%; width: 400px;height: 300px; margin-left: -200px;margin-top: -150px;}

    .other{background-color: #ccc;} / * extra styles can be removed*/
</style>

<div class="wrap">
    <div class="center other">
        <h2>The content of this layer will not be centered</h2>
    </div>
</div>

Posted on Sat, 02 May 2020 14:01:29 -0700 by Akito