inline或者inline-*元素
.center-children {
text-align: center;
}
块级元素
.center-me {
margin: 0 auto;
}
inline或者inline-*元素
仅仅是一行
.link {
padding-top: 30px;
padding-bottom: 30px;
}
多行
.flex-center-vertically {
display: flex;
justify-content: center;
flex-direction: column;
height: 400px;
}
块级元素
已知元素的高度
.parent {
position: relative;
}
.child {
position: absolute;
top: 50%;
height: 100px;
margin-top: -50px; /* account for padding and border if not using box-sizing: border-box; */
}
未知元素的高度
.parent {
position: relative;
}
.child {
position: absolute;
top: 50%;
transform: translateY(-50%);
}
使用flex
.parent {
display: flex;
flex-direction: column;
justify-content: center;
}
元素宽高固定
.parent {
position: relative;
}
.child { width: 300px; height: 100px; padding: 20px;
position: absolute; top: 50%; left: 50%;
margin: -70px 0 0 -170px; }
* 元素的宽高未知
```css
.parent {
position: relative;
}
.child {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
.parent {
display: flex;
justify-content: center;
align-items: center;
}