ThinkChat🤖让你学习和工作更高效,注册即送10W Token,即刻开启你的AI之旅 广告
## 水平垂直居中- #### 已知高度和宽度的元素: **方法一:** 设置父元素为相对定位,给子元素设置绝对定位,**top: 0; right: 0; bottom: 0; left: 0; margin: auto;** **方法二:** 设置父元素为相对定位,给子元素设置绝对定位,**left: 50%; top: 50%; margin-left: -****\-元素宽度的一半px****; margin-top: -****\-元素高度的一半px****;** #### 未知高度和宽度的元素: **方法一:使用定位属性** 设置父元素为相对定位,给子元素设置绝对定位,**left: 50%; top: 50%; transform: translateX(-50%) translateY(-50%);** **方案二:使用flex布局实现** 设置父元素为flex定位,**justify-content: center; align-items: center;** <div id="div1"> <h2> 1, 5种方法实现 flex元素水平垂直居中 </h2></div> ```javascript <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>flex元素水平垂直居中@cookie_fzx</title> <style> #wrap { width: 400px; height: 400px; background: grey; /*position: relative;*/ /*方法1: flex 新版本*/ display: flex; justify-content: center; /*水平居中*/ align-items: center; /*垂直居中*/ /*方法2: flex 老版本*/ /*display: -webkit-box;*/ /*-webkit-box-pack: center;*/ /*-webkit-box-align: center;*/ } #wrap .box { width: 150px; height: 150px; background: pink; /*方法3: top,left各50%,上移回去transform: translate(-50%, -50%) */ /*position: absolute;*/ /*top: 50%;*/ /*left: 50%;*/ /*transform: translate(-50%, -50%);*/ /*方法4: top,left各50%,上移回去margin-left和margin-top值为小盒子的一半 */ /*margin-left: -75px;*/ /*margin-top: -75px;*/ /*方法5: margin: auto */ /*left: 0;*/ /*right: 0;*/ /*top: 0;*/ /*bottom: 0;*/ /*margin: auto;*/ } </style> </head> <body> <div id="wrap"> <div class="box"></div> </div> </body> </html> ```