Summary of CSS Horizontal and Vertical Centering Method

Scheme 1: position absolute positioning + margin negative value

Applicability: Subelements have width and height dimensions
METHODS: Relative positioning of parent elements, absolute positioning of child elements, 50% of parent elements were positioned by left and top, and half of the size of child elements were moved to left and upward by margin.

.wrapper{
        background: #1890ff;
        height: 400px;
        width:400px;
        position: relative;
}
.content{
        background: #FFB90F;
        width: 200px;
        height:200px;
        position: absolute;
        left: 50%;
        top:50%;
        margin:-100px 0 0 -100px;
}

Effect:


Scheme 1

Scheme 2: position absolute positioning + transform ation adjustment

Applicable: Unknown width and height of sub-elements (of course, you can also know!)
METHODS: The first principle of this method and scheme is to replace margin with transform: translate (-50%, -50%).

.wrapper{
        background: #1890ff;
        height: 400px;
        width:400px;
        position: relative;
    }
.content{
        background: #FFB90F;
        /*width: 200px;*/
        /*height:200px;*/
        position: absolute;
        left: 50%;
        top:50%;
        transform: translate(-50%,-50%);
}

Effect:


Scheme 2. png

Scheme 3: position absolute positioning + margin: auto

Applicability: Subelements have width and height dimensions
METHODS: Relative positioning of parent elements and absolute positioning of child elements were performed. left, right, top and bottom were set to 0, then margin: auto was used.

.wrapper{
        background: #1890ff;
        height: 400px;
        width:400px;
        position: relative;
    }
.content{
        background: #FFB90F;
        width: 200px;
        height:200px;
        position: absolute;
        left: 0;
        right:0;
        top:0;
        bottom:0;
        margin:auto;
}

Effect: Same as scheme 1.

Scheme 4: flex elastic box

Applicable: Unknown width and height of sub-elements (of course, you can also know!)
Method: The parent element is set to elastic box, and justify-content and align-items are set to center.

.wrapper{
        background: #1890ff;
        height: 400px;
        width:400px;
        display: flex;
        justify-content: center;/*Centralized spindle direction*/
        align-items:center;/*Side axis centered*/
    }
.content{
        background: #FFB90F;
        /*width: 200px;*/
        /*height:200px;*/
}

Effect: The same as scheme 2.

Posted by capitala on Mon, 15 Apr 2019 12:18:32 -0700