怎么让flex布局居中
时间: 2023-11-08 10:56:13 浏览: 38
要让flex布局居中,可以使用以下方法:
1. 使用justify-content属性和align-items属性,将父容器设置为display: flex,并且设置justify-content: center和align-items: center,这样子元素就会水平和垂直居中。
示例代码如下:
```css
.flex_parent {
display: flex;
justify-content: center;
align-items: center;
}
```
2. 如果想要在垂直方向上居中,可以使用align-items: center;,如果只想在水平方向上居中,可以使用justify-content: center。
示例代码如下:
```css
.flex_parent {
display: flex;
align-items: center; /* 垂直居中 */
}
或
.flex_parent {
display: flex;
justify-content: center; /* 水平居中 */
}
```
3. 如果希望子元素在主轴上居中,可以使用justify-content: center,如果希望在交叉轴上居中,可以使用align-items: center。
示例代码如下:
```css
.flex_parent {
display: flex;
justify-content: center; /* 主轴上居中 */
}
或
.flex_parent {
display: flex;
align-items: center; /* 交叉轴上居中 */
}
```