关键代码
父类:
display: table-cell;
vertical-align: middle;
示例:
<style>
.parent {
width: 200px;
height: 600px;
background-color: blueviolet;
display: table-cell;
vertical-align: middle;
}
.son {
width: 200px;
height: 200px;
background-color: cornflowerblue;
}
</style>
</head>
<body>
<div class="parent">
<div class="son">哈哈</div>
</div>
</body>
扩展知识
vertical-align
属性:用于设置文本内容的垂直方向对齐方式
top:顶部对齐
middle:居中对齐
bottom:底部对齐
优缺点分析
vertical-algin
属性具有继承性,导致父级元素的文本也是居中显示的关键代码
父类:position: relative;
子类:
top: 50%;
transform: translateY(-50%);
示例:
<style>
.parent {
width: 200px;
height: 600px;
background-color: blueviolet;
position: relative;
}
.son {
width: 200px;
height: 200px;
background-color: cornflowerblue;
position: absolute;
top: 50%;
transform: translateY(-50%);
}
</style>
</head>
<body>
<div class="parent">
<div class="son">哈哈</div>
</div>
</body>
优缺点分析
关键代码
父类:position: relative;
子类:
position: absolute;
top: 0;
bottom: 0;
margin: auto 0;
示例
<style>
.parent {
width: 200px;
height: 600px;
background-color: blueviolet;
position: relative;
}
.son {
width: 200px;
height: 200px;
background-color: cornflowerblue;
position: absolute;
top: 0;
bottom: 0;
margin: auto 0;
}
</style>
</head>
<body>
<div class="parent">
<div class="son">哈哈</div>
</div>
</body>