Several common ways for boxes to be horizontal and vertical

1. Using absolute positioning , position top:50% and left:50% of the upper left corner of the element to the center of the page, and then use translate to adjust the center point of the element to the center of the page.
 

div{
        position:absolute;
        top:50%;
        left:50%;
        transform:translate(-50%,-50%);
        width:200px;
        height:200px;
        background-color:pink;
  
    }

2. Using absolute positioning, set the values ​​of the four directions to 0, and set the margin to auto . Since the width and height are fixed, the corresponding direction is bisected, and the centering in the horizontal and vertical directions can be realized. This method is suitable for cases where the box has width and height.

.div { 
        position: absolute;
        left: 0;
        right: 0;
        top: 0;
        bottom: 0;
        margin: auto;
        width: 200px;
        height: 200px;
        background-color:red;
    }

3. Using flex layout , set the vertical and horizontal center alignment of the container through align-items:center and justify-content:center , and then its child elements can also be vertically and horizontally centered.

.div {
        display:flex;
        justify-content:center;
        align-items:center;
        width: 100%;
        height: 100%;
        
      }

Guess you like

Origin blog.csdn.net/weixin_49054076/article/details/130694552