仅居中元素定宽高适用
- absolute + 负margin
- absolute + margin auto
- absolute + calc
居中元素不定宽高
- absolute + transform
- lineheight
- writing-mode
- table
- css-table
- flex
- grid
作者:颜海镜 链接:https://juejin.cn/post/6844903679242305544
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>未知宽高元素水平垂直居中</title>
</head>
<style>
.parent1{
display: table;
height:300px;
width: 300px;
background-color: #FD0C70;
}
.parent1 .child{
display: table-cell;
/*子元素使用了table-cell,垂直居中就可以实现*/
vertical-align: middle;
text-align: center;
color: #fff;
font-size: 16px;
}
</style>
<body>
<div class="parent1">
<div class="child">hello world-1</div>
</div>
</body>
</html>
- 子元素绝对定位,距离顶部 50%,左边50%,然后使用css3 transform:translate(-50%; -50%)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>未知宽高元素水平垂直居中</title>
</head>
<style>
.parent3{
position: relative;
height:300px;
width: 300px;
background: #FD0C70;
}
.parent3 .child{
position: absolute;
top: 50%;
left: 50%;
color: #fff;
transform: translate(-50%, -50%);
}
</style>
<body>
<div class="parent3">
<div class="child">hello world-3</div>
</div>
</body>
</html>
- flex布局