不bb,直接上代码
<!DOCTYPE html>
<html lang="en"><head>
<meta charset="UTF-8">
<title>Document</title>
<script src='c.js'></script>
<style>
body,ul,li,p{
margin:0;
padding:0;
}
div{
width:200px;
height:200px;
border:1px solid black;
position:relative;
}
p{
width:100px;
height:100px;
background: green;
position:absolute;
left:0;
bottom:0;
top:0;
right:0;
margin:auto;
}
</style>
</head>
<body>
<div class='a1'>
<p></p>
</div>
</body>
</html>
把子元素P设置为绝对定位,left,bottom,top,right都设置为0,然后设置margin:auto。
注意:相对于哪个祖先元素居中,就在哪个元素写上相对定位。