About several alignment methods of DIV
Frequently Asked Questions: What's wrong with a box inside another box, and how to make it center horizontally
1. The Flex method
Set the parent element to flexible layout: display: flex
Then set the property: justify-content: center (justify-content is used to set or retrieve the alignment of the elastic box element in the main axis (horizontal axis) direction.)
Then set the attribute: align-items: center; (the align-items attribute defines the alignment of the flex item in the direction of the lateral axis (vertical axis) of the current line of the flex container.)
display: flex;
justify-content: center;
align-items: center;
text-align: center;
2.position positioning method
You must first use absolute positioning position: absolute, if you change to relative positioning position: relative; it will only center left and right, not up and down.
.test{
background-color: red;
width:100px;
height:100px;
position:relative;
margin:200px auto;
}
.test1{
height:50px;
width:50px;
background-color:pink;
position:absolute;
text-align: center;
line-height:50px;
top: 0;
left: 0;
bottom: 0;
right: 0;
margin: auto;
}
![](https://img-blog.csdnimg.cn/20210507174947155.png)
3.position+transform method
.Positioning + transform (no need to know the width and height of the child box)
.test{
background-color:red;
width:100px;
height:100px;
position:relative;
}
.test1{
height:50px;
width:50px;
background-color:pink;
position:absolute;
top:50%;
left:50%;
transform: translate(-50% ,-50%);
}
![](https://img-blog.csdnimg.cn/20210507175014212.png)