css盒子水平垂直居中的几种方式

2023-07-12,,

第一种:son盒子中定位的上下左右全部为0,然后margin:auto

 1 <!DOCTYPE html>
2 <html lang="en">
3 <head>
4 <meta charset="UTF-8">
5 <meta http-equiv="X-UA-Compatible" content="IE=edge">
6 <meta name="viewport" content="width=device-width, initial-scale=1.0">
7 <title>Document</title>
8 <style>
9 *{
10 margin: 0;
11 padding: 0;
12 }
13 .box{
14 position: relative;
15 width: 500px;
16 height: 500px;
17 background-color: antiquewhite;
18 }
19 .son{
20 position: absolute;
21 top: 0;
22 right: 0;
23 bottom: 0;
24 left: 0;
25 margin: auto;
26 width: 200px;
27 height: 200px;
28 background-color: skyblue;
29 }
30 </style>
31 </head>
32 <body>
33 <div class="box">
34 <div class="son"></div>
35 </div>
36 </body>
37 </html>

第二种:top50%,left50%,然后使用transform: translate(-50%,-50%);   ***我最常用的

 1 <!DOCTYPE html>
2 <html lang="en">
3 <head>
4 <meta charset="UTF-8">
5 <meta http-equiv="X-UA-Compatible" content="IE=edge">
6 <meta name="viewport" content="width=device-width, initial-scale=1.0">
7 <title>Document</title>
8 <style>
9 *{
10 margin: 0;
11 padding: 0;
12 }
13 .box{
14 position: relative;
15 width: 500px;
16 height: 500px;
17 background-color: antiquewhite;
18 }
19 .son{
20 position: absolute;
21 top: 50%;
22 left: 50%;
23 transform: translate(-50%,-50%);
24 width: 200px;
25 height: 200px;
26 background-color: skyblue;
27 }
28 </style>
29 </head>
30 <body>
31 <div class="box">
32 <div class="son"></div>
33 </div>
34 </body>
35 </html>

第三种

 1 <!DOCTYPE html>
2 <html lang="en">
3 <head>
4 <meta charset="UTF-8">
5 <meta http-equiv="X-UA-Compatible" content="IE=edge">
6 <meta name="viewport" content="width=device-width, initial-scale=1.0">
7 <title>Document</title>
8 <style>
9 *{
10 margin: 0;
11 padding: 0;
12 }
13 .box{
14 position: relative;
15 width: 500px;
16 height: 500px;
17 background-color: antiquewhite;
18 }
19 .son{
20 position: absolute;
21 top: 50%;
22 left: 50%;
23 margin: -100px -100px;
24 width: 200px;
25 height: 200px;
26 background-color: skyblue;
27 }
28 </style>
29 </head>
30 <body>
31 <div class="box">
32 <div class="son"></div>
33 </div>
34 </body>
35 </html>

css盒子水平垂直居中几种方式的相关教程结束。

《css盒子水平垂直居中的几种方式.doc》

下载本文的Word格式文档,以方便收藏与打印。