首页 > Web开发 > 详细

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

时间:2021-02-05 19:11:07      阅读:19      评论:0      收藏:0      [点我收藏+]

一,已知宽高

 

 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;
}

 

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

原文:https://www.cnblogs.com/shun1015/p/14378436.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!