.parent { width: 500px; /* 为了显示方便,与本文知识点无关 */ background-color: teal; /* 为了显示方便,与本文知识点无关 */ height: 300px; position: relative; } .child { background-color: tomato; color: #fff; width: 100px; position: absolute; top: 50%; transform: translateY(-50%); }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>块级元素垂直居中</title> </head> <body> <div class="parent"> <div class="child"> 我是块级元素,我要垂直居中 </div> </div> </body> </html>