让元素水平垂直居中的四种方法 曾经终败给现在 2022-11-27 07:09 123阅读 0赞 ### 一、使用flex弹性布局 ### <!DOCTYPE html> <html> <head> <meta charset="utf-8"/> <title>flex</title> </head> <style> *{ margin: 0; padding: 0; } #father{ display: flex; justify-content: center; align-items: center; background-color: black; height:100vh; } #son{ width: 50%; height: 50%; background-color: white; } </style> <body> <div id="father"><div id="son"></div></div> </body> </html> ### 二、使用transform变形 ### 将子元素的宽和高设置为百分数,如宽设置为 80%,则需要向 X 轴偏移 10%;那么 translateX 为10/80 = 0.125,即 12.5%;如果高设置为 60%,则需要向 Y 轴偏移 20%,那么 translateY 为20/60 = 33%,即子元素需要设置 transfrom:translate(12.5%,33%)。 <!DOCTYPE html> <html> <head> <meta charset="utf-8"/> <title>transform</title> </head> <style> *{ margin: 0; padding: 0; } #father{ background: black; height:100vh; } #son{ width: 50%; height: 50%; background: white; transform: translate(50%,50%); } </style> <body> <div id="father"><div id="son"></div></div> </body> </html> ### 三、使用position定位 ### 将父元素设置为 positon:fixed,然后上下左右都为 0;使其填满整个屏幕; 子元素也设置为 positon:fixed,然后上下左右都为 0;margin 设置为 auto,实现水平垂直居中。 <!DOCTYPE html> <html> <head> <meta charset="utf-8"/> <title>position</title> </head> <style> *{ margin: 0; padding: 0; } #father{ background: black; position:fixed; left:0; right:0; top:0; bottom:0; } #son{ width: 50%; height: 50%; background: white; margin:auto; position:fixed; left:0; right:0; top:0; bottom:0; } </style> <body> <div id="father"><div id="son"></div></div> </body> </html> ### 四、transform 与 position 结合 ### 将父元素设置为 positon:fixed,然后上下左右都为 0;使其填满整个屏幕 子元素也设置为 positon:fixed,然后上下各设为 50%;即位置到达中心点,但是元素也有高宽度,所以整体就偏移了,应当上下都回退25%的距离,即设置为 transform:translate(-50%,-50%)。 <!DOCTYPE html> <html> <head> <meta charset="utf-8"/> <title>position-transform</title> </head> <style> *{ margin: 0; padding: 0; } #father{ background: black; position:fixed; left:0; right:0; top:0; bottom:0; } #son{ width: 50%; height: 50%; background: white; position:fixed; left:25%; top:25%; transform: translateY(-50%,-50%); } </style> <body> <div id="father"><div id="son"></div></div> </body> </html>
还没有评论,来说两句吧...