JSFiddle - React, Tailwind, and code Playground
by cj1406942109
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>块级元素垂直居中</title>
</head>
<body>
<div class="parent">
<div class="child">
我是块级元素,我要垂直居中
</div>
</div>
</body>
</html>
CSS
.parent {
border: 1px solid transparent; /* 避免外边距合并,与本文知识点无关 */
width: 500px; /* 为了显示方便,与本文知识点无关 */
background-color: teal; /* 为了显示方便,与本文知识点无关 */
/* 重要前提, 父元素高度已知*/
height: 300px;
}
.child {
background-color: tomato;
color: #fff;
width: 100px;
height: 100px;
margin: 100px auto 0;
/* transform: translateY(-50%); */
}