方法一:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
#div1{
width:300px;
height:300px;
background-color: skyblue;
position: relative;
}
p{
width:100px;
height: 100px;
position:absolute;
left: 0;
right: 0;
top: 0;
bottom: 0;
margin:auto;
background-color: red;
} </style>
</head>
<body>
<div id="div1">
<p></p>
</div>
</body>
</html>
方法二:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
#div1{
width:300px;
height:300px;
background-color:skyblue;
position: relative;
}
p{
width:100px;
height:100px;
background-color: red;
position: absolute;
top: 50%;
left: 50%;
margin-top:-50px;
margin-left:-50px;
}
</style>
</head>
<body>
<div id="div1">
<p></p>
</div>
</body>
</html>
方法三:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>index</title>
<style>
div {
display: table-cell;
width: 200px;
height: 200px;
text-align: center;
vertical-align: middle;
border: 1px solid #F00;
}
</style>
</head>
<body>
<div>
<p>123nonosfnfon</p>
</div>
</body>
</html>
方法四:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
#div1{
width:300px;
height:300px;
background-color:skyblue;
overflow: hidden;
}
p{
width:100px;
height:100px;
background-color: red;
margin:0 auto;
position:relative;
top:50%;
margin-top:-50px;
}
</style>
</head>
<body>
<div id="div1">
<p></p>
</div>
</body>
</html>
方法五:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
#div1{
width:300px;
height:300px;
background-color:skyblue; }
p{
width: 100px;
height: 100px;
background: red;
margin: 0 auto; /*水平居中*/
position: relative;
top: 50%; /*偏移*/
transform: translateY(-50%);
}
</style>
</head>
<body>
<div id="div1">
<p></p>
</div>
</body>
</html>
方法六:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
#div1{
width:300px;
height:300px;
background-color:skyblue;
display: flex;
display: -webkit-flex;
align-items: center;
justify-content: center; }
p{
width: 100px;
height: 100px;
background: red;
}
</style>
</head>
<body>
<div id="div1">
<p></p>
</div>
</body>
</html>
如果你还有其他的方法欢迎在下评论