1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>Title</title> 6 </head> 7 8 <style> 9 *{ 10 margin: 0; 11 padding: 0; 12 } 13 .main{ 14 width:300px; 15 height:400px; 16 position: relative; 17 top:0; 18 left:0; 19 background-color: antiquewhite; 20 } 21 .center{ 22 position: absolute; 23 width:100px; 24 height:100px; 25 top:50%; 26 left:50%; 27 background-color: red; 28 transform: translate(-50%,-50%); 29 } 30 31 </style> 32 <body> 33 34 35 <div class="main"> 36 <div class="center"> 37 </div> 38 </div> 39 </body> 40 </html>
效果:
第二种:flex布局垂直居中
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>Title</title> 6 7 <style> 8 html,body { 9 width: 100%; 10 height: 100%; 11 margin: 0; 12 padding: 0; 13 } 14 15 .main{ 16 position: absolute; 17 display: flex; 18 align-items:center; 19 justify-content: center; 20 width:500px; 21 height:600px; 22 background-color: orange; 23 24 } 25 .content { 26 width:300px; 27 height:300px; 28 background-color: red; 29 } 30 </style> 31 </head> 32 <body> 33 <div class="main"> 34 <div class="content"></div> 35 </div> 36 37 </body> 38 </html>
效果:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<style>
*{
margin: 0;
padding: 0;
}
.main{
width:300px;
height:400px;
position: relative;
top:0;
left:0;
background-color: antiquewhite;
}
.center{
position: absolute;
width:100px;
height:100px;
top:50%;
left:50%;
background-color: red;
transform: translate(-50%,-50%);
}
</style>
<body>
<div class="main">
<div class="center">
</div>
</div>
</body>
</html>