Flex布局原理

1.布局原理

flex 是 flexible Box 的缩写,意为"弹性布局",用来为盒状模型提供最大的灵活性,任何一个容器都可以 指定为 flex 布局。
当我们为父盒子设为 flex 布局以后,子元素的 float、clear 和 vertical-align 属性将失效。
伸缩布局 = 弹性布局 = 伸缩盒布局 = 弹性盒布局 =flex布局

2.flex布局父项常见属性

flex-direction:

主轴和侧轴:

默认主轴是x轴方向,水平向右;

默认侧轴是y轴方向,水平向下

css 复制代码
    <style>
        div {
            /* 给父级添加flex属性 */
            display: flex;
            width: 800px;
            height: 300px;
            background-color: pink;
            /* 默认的主轴是 x 轴 行 row  那么y轴就是侧轴喽 */
            /* 我们的元素是跟着主轴来排列的 */
            /* flex-direction: row; */
            /* 简单了解 翻转 */
            flex-direction: row-reverse;
            /* 我们可以把我们的主轴设置为 y轴 那么 x 轴就成了侧轴 */
            flex-direction: column;
        }
        
        div span {
            width: 150px;
            height: 100px;
            background-color: purple;
        }
    </style>

justify-content(设置主轴上的子元素的排列方式)

flex-wrap 设置子元素是否换行
默认情况下,项目都排在一条线(又称"轴线")上。flex-wrap属性定义,flex布局中默认是不换行的

属性值:no-wrap(换行)、wrap(默认值换行)

align-items

设置侧轴上的子元素排列方式(单行 )

css 复制代码
div {
    display: flex;
    width: 800px;
    height: 400px;
    background-color: pink;
    /* 默认的主轴是 x 轴 row */
    flex-direction: column;
    justify-content: center;
    /* 我们需要一个侧轴居中 */
    /* 拉伸,但是子盒子不要给高度 
    /* align-items: stretch; */
    align-items: center;
    /* align-content: center; */
}

align-content

适应于换行(多行)的情况下,可设置上对齐、下对齐、居中、拉伸以及平均分配剩余空间等属性值。

单行找align-item多行找align-conten

flex:属性定义子项目分配剩余空间,用flex来表示占多少份数

align-self:控制子项在自己在侧轴上的排列方式

order:定义项目的排列顺序

css 复制代码
  <style>
    section {
      display: flex;
      width: 60%;
      height: 150px;
      background-color: pink;
      margin: 100px auto;
      /* justify-content: center; */
      /* align-items: center; */
    }

    section div {
      background-color: purple;
      margin-right: 5px;
      width: 100px;
      height: 50px;
    }
    section div:nth-child(2) {
    /* 默认是0   -1比0小所以在前面 */
      order: -1;
      background-color: greenyellow;
    }
    section div:nth-child(3) {
      align-self: flex-end;
    }
  </style>

背景渐变必须添加浏览器私有前缀

css 复制代码
/* background: -webkit-linear-gradient(left, red, blue); */
/* background: -webkit-linear-gradient(red, blue); */
background: -webkit-linear-gradient(top left, rgb(22, 173, 67), rgb(71, 10, 212));
相关推荐
遇到困难睡大觉哈哈1 天前
Harmony os 静态卡片(ArkTS + FormLink)详细介绍
前端·microsoft·harmonyos·鸿蒙
用户47949283569151 天前
Bun 卖身 Anthropic!尤雨溪神吐槽:OpenAI 你需要工具链吗?
前端·openai·bun
p***43481 天前
前端在移动端中的网络请求优化
前端
g***B7381 天前
前端在移动端中的Ionic
前端
拿破轮1 天前
使用通义灵码解决复杂正则表达式替换字符串的问题.
java·服务器·前端
whltaoin1 天前
【 Web认证 】Cookie、Session 与 JWT Token:Web 认证机制的原理、实现与对比
前端·web·jwt·cookie·session·认证机制
Aerelin1 天前
爬虫playwright入门讲解
前端·javascript·html·playwright
5***o5001 天前
前端在移动端中的NativeBase
前端
灵魂学者1 天前
Vue3.x —— 父子通信
前端·javascript·vue.js·github
1***Q7841 天前
前端跨域解决方案
前端