css实现水平垂直居中的几种方法

一,已知宽高

 

 1         <style>
 2             #box {
 3                 height: 400px;
 4                 width: 400px;
 5                 border: 1px solid grey;
 6                 position: relative;
 7             }
 8             .son {
 9                 height: 300px;
10                 width: 300px;
11                 border: 1px solid grey;15                 
16                 
17             }
18         </style>
19     </head>
20     <body>
21         <div id="box">
22             <div class="son">
23                 已知宽高
24             </div>
25         </div>
26     </body>

 

1. (absolute+负maigin)

1 position: absolute;                    
2 top: 50%;
3 left: 50%;
4 margin-top: -150px;
5 margin-left: -150px;

 2. (absolute+maigin:auto)

1 position: absolute;
2 top: 0;
3 left: 0;
4 right: 0;
5 bottom: 0;
6 margin: auto;

 

3.(absolute+calc)

  这里的50%是父元素宽高的50%

1 position: absolute;
2 top:calc(50% - 150px);
3 left:calc(50% - 150px);

4 (父元素display:flex;子元素:margin: auto)

1 #box {            
2         display: flex;
3    }
4 .son {
5       margin: auto;
6 }

二、未知宽高

1,absolute+transform(依赖translate 2d的兼容性)

1 position:absolute;
2 top:50%;
3 left:50%;
4 transform:translate(-50%,-50%);

2,利用flex布局

#box {
    display: flex;
    align-items: center;
    justify-content: center;
}

 

posted @ 2021-02-05 16:24  顺·  阅读(202)  评论(0编辑  收藏  举报