CSS 属性非常强大和灵活,可以帮助我们控制 web 页面中的元素的布局和样式。其中,上下对齐方式是一个非常重要且常用的属性,下面介绍一些实现方式。 垂直居中当我们在网页中需要将一个元素垂直居中时,可...
CSS 属性非常强大和灵活,可以帮助我们控制 web 页面中的元素的布局和样式。其中,上下对齐方式是一个非常重要且常用的属性,下面介绍一些实现方式。
## 垂直居中
当我们在网页中需要将一个元素垂直居中时,可以使用以下方法:
### 行高+line-height
css
.container {
height: 300px;
border: 1px solid #ccc;
text-align: center;
line-height: 300px;
} css
.container {
height: 300px;
border: 1px solid #ccc;
display: flex;
align-items: center;
justify-content: center;
} css
.container {
height: 300px;
border: 1px solid #ccc;
display: table;
margin: 0 auto;
}
.item {
display: table-cell;
vertical-align: middle;
} css
.container {
position: relative;
height: 300px;
border: 1px solid #ccc;
}
.item {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
} css
.container {
height: 200px;
border: 1px solid #ccc;
line-height: 200px;
}
.item {
vertical-align: middle;
display: inline-block;
} css
.container {
height: 200px;
border: 1px solid #ccc;
display: flex;
align-items: center;
}
.item {
flex: 1;
} css
.container {
height: 200px;
border: 1px solid #ccc;
display: grid;
grid-template-columns: 1fr 1fr;
grid-template-rows: 1fr;
align-items: center;
}
.item {
display: flex;
justify-content: center;
} css
.container {
height: 200px;
border: 1px solid #ccc;
position: relative;
}
.item {
position: absolute;
top: 50%;
transform: translateY(-50%);
}