CSS|flex与grid布局

210 阅读2分钟

flex布局

初识

开启flex布局只需在最外层容器设置display:flex即可

采用flex布局称之为flex容器,所有子容器自动生成容器成员,成为flex项目

开启flex布局后,flex项目会沿着主轴横向排列

image.png

容器属性

justify-content:(横轴属性)

justify-content:center 沿着横轴方向进行居中对齐

justify-content:flex-end靠右对齐

justify-content:space-between左右两端对齐,且项目之间的间距相等

justify-content:space-around项目之间的间距为左右容器到项目间距的二倍

justify-content:space-evenly项目之间间距与容器与容器之间间距相等

align-items:(纵轴属性)

align-items:flex-star为默认位置(横向)

align-items:center居中排列

align-items:flex-end靠着交叉轴底部对齐

当这两个属性都设置为center时,这个项目就会水平垂直居中

flex-direction:

flex-direction:row(默认值)按行排列

flex-direction:row-reverse 逆序排列

flex-direction:column 按列分布(也就是竖直排列)

flex-direction:column-reverse按列分布,逆序排列

flex-wrap:

flex-wrap:nowrap 当项目总宽度大于容器宽度时,项目会强行等分容器宽度且不换行

flex-wrap:wrap 项目会根据自身宽度进行排列,如果超出容器宽度则自动换行

项目属性(设置在项目自身上)

给每个具体的小项目item设置

order:数字

数字越小,项目排列越靠前

flex-grow:

1/0 image.png

flex-shrink:

1/0 image.png

flex-basis:

用于设置项目宽度,权重高于width属性 image.png

flex属性合并

flex-grow/shrink/basis(放大/缩小/宽度) image.png auto(1 auto auto)等分放大缩小

none(0 0 auto)不放大,但等分缩小

align-self:

可操纵单个项目的排列

align-self:center居中

align-self:flex-end靠底端对齐

总的来说

水平和垂直的设置分别为:

image.png

grid布局(二维布局方式)

开启grid布局,只需给外层容器设置 display:grid

grid-template-columns:(可用于做几栏布局)

用于设置每列的宽度,有几列,就写几个宽度

px(固定宽度)/fr(浮动宽度)


1fr,三列各三分之一 image.png 2fr占据二分之一的空间 联想截图_20231115214240.png

间距

column-gap:(列间距)

row-gap:(行间距)

gap:(统一设置)

grid-template-areas:(用于整体布局排列元素)

例如 想要实现这样的比例(中间sidebar占三分之一,content占三分之二) image.png 那么就给整体设置: image.png 各个元素分别指定对应区域: image.png

容器属性

align-content:

align-content:center居中

align-content:end靠下

justify-content:

justify-content:center居中

justify-content:end靠右

项目属性

align-items:

align-items:center

align-items:end

justify-items:

justify-items:center居中

justify-items:end靠右

justify-items:space-between两端