<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title></title> </head> <style> html, body { /*body 存在边距*/ margin: 0; width: 100%; height: 100%; } .parentElement { width: 100%; height: 100%; background-color: yellow; } .childElement { background-color: red; width: 100px; height: 100px; } /* 第一种 无兼容性问题,但需要知道居中元素的宽和高*/ /*相对定位和固定定位会脱离标准流*/ .parentElement-one { position: relative; } .childElement-one { position: absolute; left: 50%; margin-right: -50px; top: 50%; margin-top: -50px; } /*兼容IE10以上*/ /*第二种*/ .parentElement-two { position: relative; } .childElement-two { position: absolute; left: 50%; top: 50%; transform: translate(-50%, -50%); } /*第三种*/ .childElement-three { position: relative; left: 50%; top: 50%; transform: translate(-50%, -50%); } /*第四种*/ .parentElement-fore { display: flex; /*垂直方向对齐*/ align-items: center; /*水平方向对齐*/ justify-content: center; } /*兼容IE10以上*/ /*第五种 水平居中*/ /*行内元素 设置 text-align:center (文本, 给父元素设置)水平居中*/ /*父元素高度确定的单行文本: height = line-height 垂直居中*/ /*父元素高度确定的多行文本(行内块): 先设置 display:table-cell 再设置 vertical-align:middle*/ .childElement { /*margin: 0 auto;*/ text-align:center } </style> <body> <div class="parentElement"> <div class="childElement"> <span>dd</span> </div> </div> </body> </html>
css元素居中的多个方法
猜你喜欢
转载自blog.csdn.net/zsnpromsie/article/details/80286318
今日推荐
周排行