设置元素水平、垂直居中的两种方式

  做一个水平和垂直居中的模态弹框这么一个小需求,对于我们这些前端来说,应该是常事。

  在css3出来以前,我们要想让元素既水平居中又要垂直居中只有一个办法(我能想到的),就是通过js计算,把它们定位到屏幕中间位置。这方法比较笨,也麻烦。

 

  下面两种方式,可以让元素快速定位到屏幕中间。 

  flex布局

 1 <style>
 2     .flex-mask {
 3         display: flex;
 4         position: fixed;
 5         z-index: 1;
 6         top: 0;
 7         left: 0;
 8         bottom: 0;
 9         right: 0;
10         align-items: center;  // 垂直居中
11         justify-content: center;  // 水平居中
12         background: rgba(0,0,0,.5);
13     }
14     .flex-box {
15         width: 500px;
16         height: 300px;
17         background-color: #fff;
18         border-radius: 10px;
19     }
20 </style>
21 
22 <!-- 元素 -->
23 <div class="flex-mask">
24     <div class="flex-box"></div>
25 </div>

 

 

  使用translate

 1 <style>
 2     .transform-box {
 3         position: fixed;
 4         z-index: 2;
 5         top: 50%;
 6         left: 50%;
 7         width: 300px;
 8         height: 150px;
 9         background-color: red;
10         border-radius: 10px;
11         transform: translate(-50%, -50%);
12     }
13 </style>
14 
15 <div class="transform-box"></div>

 

posted @ 2017-10-19 19:28  潘大胖  阅读(405)  评论(1编辑  收藏  举报