1 <div class='box' style="text-align: center;">hello world</div>
1 <div class="box2" style="width:150px;height:100px;line-height: 100px;">文本垂直水平居中</div>
flex布局会让容器内的元素获得垂直水平居中css
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta charset="utf-8"> 5 <title>登录</title> 6 <style type="text/css"> 7 html{width: 100%;height: 100%;} /*整个页面的居中*/ 8 body{ 9 width: 100%; 10 height: 100%; 11 display: flex; /*flex弹性布局*/ 12 justify-content: center; 13 align-items: center; 14 } 15 #login{ 16 width: 300px; 17 height: 300px; 18 border: 1px black solid; 19 display: flex; 20 flex-direction: column; /*元素的排列方向为垂直*/ 21 justify-content: center; /*水平居中对齐*/ 22 align-items: center; /*垂直居中对齐*/ 23 } 24 </style> 25 </head> 26 <body> 27 <div id="login"> 28 <h1>登录</h1> 29 <input type="text"><br> 30 <input type="password"><br> 31 <button>肯定</button> 32 </div> 33 </body> 34 </html>
1 body{ 2 width: 100%; 3 height: 100%; 4 display: -webkit-box; /*flex弹性布局*/ 5 -webkit-box-align: center; 6 -webkit-box-pack: center; 7 }
display:flex和display:box均可用于弹性布局实现水平垂直居中,不一样的是display:box是2009年的命名,已通过时,用的时候须要加上前缀;display:flex是2012年以后的命名html
CSS代码:web
<style> .box{ width: 150px; height: 150px; background:blue; position: relative; } p{ width: 50px; height: 50px; background:red; position: absolute; left:50%; top:50%; margin-left:-25px; margin-top: -25px; display: flex; align-items: center; justify-content: center; } </style>
HTML代码:布局
1 <div class="box"><p>A</p></div>
1 <style> 2 *{padding: 0;margin: 0;} /*解决容器内元素.div是p元素产生的居中不完整*/ 3 .box{ 4 margin: 20px auto; 5 width: 150px;height: 150px; 6 background:blue; 7 position: relative; 8 text-align: center; 9 } 10 .box .div1{ 11 position: absolute; 12 top:50%; 13 left:50%; 14 width:100%; 15 transform:translate(-50%,-50%); 16 text-align: center; 17 background: red 18 } 19 </style>
说明:/*通常状况下子元素不能是p元素,不然非彻底居中,P元素自带有padding距离*/,.div1若是必须是p元素则必须加上*{margin:0;padding:0;};进行初始化,flex
1 .box p{ 2 width:50%; 3 height: 50%; 4 overflow: auto; 5 position: absolute; 6 background:red; 7 margin: auto; 8 top:0; 9 bottom:0; 10 left:0; 11 right:0; 12 }
1 .box{ 2 width: 150px;height: 150px; 3 background:blue; 4 position: relative; 5 text-align: center; 6 display: table-cell; 7 vertical-align: middle; 8 }
缺点:对容器.box的子元素的设置宽高会形成失效。spa