Several common ways to center the box shown vertically and horizontally within a page
- Positioning method +margin(know the actual width and height of the box)
.box {
width: 100px;
height: 100px;
background: blueviolet;
position: absolute;
left: 50%;
top: 50%;
margin-top: -50px;
margin-left: -50px;
}
Copy the code
2. Position +transform(no need to know the actual width and height of the box)
.box {
width: 100px;
height: 100px;
background: blueviolet;
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}
Copy the code
3. Flex layout (parent element)
body {
position: relative;
height: 100vh;
display: flex;
align-items: center;
justify-content: center;
}
.box {
width: 100px;
height: 100px;
background: blueviolet;
}
Copy the code
4. Display: table-cell is incompatible
.box {
width: 100px;
height: 100px;
background: blueviolet;
display: table-cell;
text-align: center;
vertical-align: middle;
}
Copy the code