div{ width: 200px; height: 100px; background-color: pink; display: flex; flex-direction: row; justify-content: center; align-items: center; }
在CSS中,我们可以使用flex布局来让元素对齐。
flex布局是一种基于交叉轴和主轴来对齐元素的一种布局方式。
其中,主轴是元素流动的方向,交叉轴是垂直于主轴的方向。
假如我们要让一个div水平垂直居中,我们可以先设定div为flex布局,然后设置flex-direction属性为row,justify-content属性为center,align-items属性为center。
div{
display: flex; // 设置为flex布局
flex-direction: row; // 设置为水平方向
justify-content: center; // 在主轴上居中
align-items: center; // 在交叉轴上居中
}