在页面布局中,元素水平垂直居中的方法有很多,这里就列举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%); */ }
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。
评论(0)