-
已知元素高度
方式一:<html> <head> <style> .box { width: 200px; height: 200px; position: relative; } .content { width: 40px; height: 40px; background: lightgray; position: relative; margin: 0 auto; /* 水平居中 */ top: 50%; /* 顶部与box中线对齐 */ margin-top: -20px; /* 中心与box中线对齐 */ } </style> </head> <body> <div class="box"> <div class="content"></div> </div> </body> </html>
方式二:
<html> <head> <style> .box { width: 200px; height: 200px; position: relative; } .content { width: 40px; height: 40px; background: lightgray; position: absolute; margin: auto; top: 0; bottom: 0; left: 0; right: 0; } </style> </head> <body> <div class="box"> <div class="content"></div> </div> </body> </html>
-
未知元素高度
<html> <head> <style> .box { width: 200px; height: 200px; position: relative; } .content { background: lightgray; position: absolute; left: 50%; /* 左边与竖直中线对齐 */ top: 50%; /* 上边与水平中线对齐 */ transform: translate(-50%, -50%); /* 向左和向上移动当前元素的50% */ } </style> </head> <body> <div class="box"> <div class="content">居中</div> </div> </body> </html>
-
flex布局
<html> <head> <style> .box { width: 200px; height: 200px; display: flex; justify-content: center; /* 水平居中 */ align-items: center; /* 垂直居中 */ } .content { background: lightgray; } </style> </head> <body> <div class="box"> <div class="content"></div> </div> </body> </html>
-
before伪元素+vertical-align: middle;
<html> <head> <style> .box { width: 200px; height: 200px; text-align: center; font-size: 0; border: 1px dotted #f00; } .box:before { content: ""; height: 100%; width: 0; vertical-align: middle; } .content { background: lightgray; font-size: 14px; display: inline-block; } </style> </head> <body> <div class="box"> <div class="content">居中</div> </div> </body> </html>
-
grid布局
<html> <head> <style> .box { width: 200px; height: 200px; display: grid; justify-content: center; align-content: center; border: 1px dotted #f00; } .content { background: lightgray; } </style> </head> <body> <div class="box"> <div class="content">居中</div> </div> </body> </html>
css元素垂直和水平居中
于 2022-03-30 18:09:43 首次发布