flex布局笔记

299 阅读3分钟

flex布局极大的提高了我们布局的效率,更简单、灵活。 image.png

display: flex; 一定要给父标签

主轴对齐方式

属性值作用
flex-start默认值, 起点开始依次排列
flex-end终点开始依次排列
center沿主轴居中排列
space-around弹性盒子沿主轴均匀排列, 空白间距均分在弹性盒子两侧
space-between弹性盒子沿主轴均匀排列, 空白间距均分在相邻盒子之间
space-evenly弹性盒子沿主轴均匀排列, 弹性盒子与容器之间间距相等

其中最常用的是space-between

justify-content: space-between;
显示效果:两侧边缘没有缝隙 image.png

justify-content: space-around;
显示效果:盒子中间的缝隙宽度是边缘的2倍 image.png

justify-content: space-evenly;
显示效果:盒子中间的缝隙和边缘都相等 image.png

justify-content: center;
显示效果:全部盒子挤在中间 image.png

记忆:

  1. 两侧没缝隙是 between
  2. 缝隙一样大是 evenly
  3. 2倍缝隙是 around

技巧:

image.png
见到这个效果,最简单的做法就是: 给大盒一个左右的padding, 然后在加 justify-content: space-between

侧轴对齐方式

属性值作用
flex-start起点开始依次排列
flex-end终点开始依次排列
center沿侧轴居中排列
stretch默认效果, 弹性盒子沿着侧轴线被拉伸至铺满容器

center ,可以让元素垂直居中。

align-items: center; 通过flex让一个子盒子水平和垂直居中

image.png

.father {
    width: 500px;
    height: 500px;
    background-color: skyblue;
    /* 设置为flex布局 */
    display: flex;
    /* 主轴水平居中 */
    justify-content: center;
    /* 侧轴垂直居中 */
    align-items: center;
}

.son {
    width: 300px;
    height: 300px;
    background-color: tomato;
}

伸缩比

把父盒子分为若干份数,每个子盒子各占几份。

flex:1; 添加给子盒子

分配父盒子的剩余的空间

语法:

.father {
    display: flex;
    height: 300px;
    width: 300px;
    background-color: skyblue;
}
.box1{
    background-color: tomato;
    flex: 1;
}
.box2{
    background-color: teal;
    flex: 2;
    
}
.box3{
    background-color: yellowgreen;
    flex: 3;

image.png

  1. 一定是添加到子盒子。
  2. 子盒子默认高度会和父盒子一样高。(前提是不给高度)

圣杯布局

所谓的圣杯布局就是左右两边大小固定不变,中间宽度自适应。

一般这种布局方式适用于各种移动端顶部搜索部分,这是最常见的,如京东手机版主页面顶部搜索

image.png 核心思路:

  • 两侧盒子写固定大小
  • 中间盒子 flex: 1; 占满剩余空间
.top {
    display: flex;
    justify-content: c;
}

.top div:first-child {
    width: 50px;
    height: 50px;
    background-color: red;
}

.top div:last-child {
    width: 50px;
    height: 50px;
    background-color: red;
}

.top div:nth-child(2) {
    flex: 1;
    height: 50px;
    background-color: pink;
}

注意:中间flex: 1; 和 width 有冲突。 优先执行 flex:1;

  1. 在flex眼中,标签不再分类。

    • 简单说就是没有块级元素,行内元素和行内块元素
    • 任何一个元素都可以直接给宽度和高度一行显示
  2. Flex不存在脱标的情况:也就是基本淘汰了浮动,更不用清除浮动

  3. 当然存在兼容性问题,如果不考虑兼容性可以大量使用,如果是移动端则不用考虑直接flex 转载非原创,仅作为学习笔记