CSS 实现水平和垂直居中的方法有多种,以下是其中几种常用的方法:
在父元素中设置 display: flex 和 justify-content: center; align-items: center; 即可实现水平和垂直居中。
.parent {
display: flex;
justify-content: center;
align-items: center;
}
在子元素中设置 position: absolute 和 top: 50%; left: 50%; transform: translate(-50%, -50%); 即可实现水平和垂直居中。
.child {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
在父元素中设置 display: table 和 text-align: center; vertical-align: middle; 在子元素中设置 display: table-cell,即可实现水平和垂直居中。
.parent {
display: table;
text-align: center;
vertical-align: middle;
}
.child {
display: table-cell;
}
需要注意的是,以上方法中的父元素和子元素都需要有指定的宽度和高度才能实现居中。其中,Flexbox 布局和绝对定位和 transform 属性方法更为常用。