方法一-定位父相子绝:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
body,div,p,ul,li {
margin:0;
padding:0;
}
.box {
position: relative;
width: 1000px;
height: 600px;
background-color: pink;
margin: 100px auto 0;
}
.min {
position: absolute;
top:0;
left: 0;
right: 0;
bottom: 0;
width: 200px;
height: 200px;
background-color:orange;
margin:auto;
}
</style>
</head>
<body>
<div class="box">
<div class="min">
</div>
</div>
</body>
</html>
如果不写宽高,里面的盒子会为父级的100%,跟父级一样大
使用此方法,必须定宽高
方法二-定位父相子绝:
.box {
position: relative;
width: 1000px;
height: 600px;
background-color: pink;
margin: 100px auto 0;
}
.min {
position: absolute;
top:50%;
left: 50%;
width: 200px;
height: 200px;
background-color:orange;
margin-top:-100px;
margin-left: -100px;
}
此方法如果更改了子盒子的宽高,需要算出margin的数值在手动调整,不是很方便
方法三-表格特性:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
body,div,p,ul,li {
margin:0;
padding:0;
}
.box {
display: table-cell;
vertical-align: middle;
width: 1000px;
height: 600px;
background-color: pink;
margin: 100px auto 0;
}
.min {
width: 200px;
height: 200px;
background-color:orange;
margin: 0 auto;
}
</style>
</head>
<body>
<div class="box">
<div class="min">
</div>
</div>
</body>
</html>
方法四-最优方法:
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50% , -50%);
更优秀的实现元素水平垂直居中
和我们的相对定位一模一样
代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
body,div,p,ul,li {
margin:0;
padding:0;
}
.box {
width: 1000px;
height: 600px;
background-color: pink;
margin: 100px auto 0;
}
.min {
position:relative;
position: absolute;
left: 50%;
top: 50%;
width: 200px;
height: 200px;
background-color: skyblue;
transform: translate(-50%,-50%);
}
</style>
</head>
<body>
<div class="box">
<div class="min">
</div>
</div>
</body>
</html>
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。