The first: absolute positioning + negative margin
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>垂直水平居中</title>
<style>
.parent{
width: 400px;
height: 400px;
margin: 100px auto auto 600px;
border: 1px solid #ccc;
position: relative;
}
.box{
width: 200px;
height: 200px;
background-color: pink;
position: absolute;
top: 50%;
left: 50%;
margin-left: -100px;
margin-top: -100px;
}
</style>
</head>
<body>
<div class="parent">
<div class="box"></div>
</div>
</body>
</html>
effect:
Note that if it is relative to the browser window, position: relative;
The second: use the css3 attribute transform
.box{
width: 200px;
height: 200px;
background-color: pink;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);//往上(x轴),左(y轴)移动自身长宽的 50%,使其居于中心位置
}
The third type: use flex layout
Fourth: Use table-cell
Take a look at the effect:
Note that I set the margin, but the parent element does not reflect this. This is because the set table-cell
element does margin
not respond to the value, but it can be padding
set in response , and when using this attribute, do not use it float属性和position:absolute;
together.