页面元素水平垂直居中

  • 页面元素水平垂直居中已关闭评论
  • 117 次浏览
  • A+
所属分类:Web前端
摘要

在页面布局中,元素水平垂直居中的方法有很多,这里就列举3个简单,用的比较多的方法吧。

在页面布局中,元素水平垂直居中的方法有很多,这里就列举3个简单,用的比较多的方法吧。

情况一、已知元素的宽高

 1     <style>  2         .center {  3             width: 200px;  4             height: 200px;  5             background-color: #000;  6             /* 1.绝对定位,加margin */  7             position: absolute;  8             left: 50%;  9             top: 50%; 10             margin-top: -100px; 11             margin-left: -100px;
12 } 13 </style> 14 </head> 15 <body> 16 <div class="center"></div> 17 </body>

情况二、未知元素的宽高

body {             /* 3.flex */             width: 600px;             height: 600px;             display: flex;              /* 主轴居中 */             justify-content: center;             /* 侧轴剧中 */             align-items: center                 }         .center {             width: 200px;             height: 200px;             background-color: #000;             /* 2.绝对定位+transform: ; */             /* position: absolute;             left: 50%;             top: 50%;             transform: translate(-50%,-50%); */              }