Skip to content
On this page

项目总结

scss 的 0 带单位

否则参与calc计算时,会报错。

修改 stylelint,确保其带单位

js
{
  rules: {
    // NOTE 忽略这个规则,因为不带单位的 0 参与 calc 计算时,报错
    'length-zero-no-unit': null
  }
}

flex 布局 ——- 既平分一行的快件又可换行,如何设置?

flex-space

html
<template>
  <div class="sy-component desc-info">
    <DescItem
      v-for="(item, index) in descList"
      :key="index"
      :label="item.label"
      :value="data?.[item.prop]" />
  </div>
</template>

<style lang="scss">
.sy-component.desc-info {
  display: flex;
  flex-flow: row wrap;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 20px;
}
</style>

上图的效果,希望每行有 3 个 item,且 item 之间平分一行的空间,当最后一行不到 3 个时,从开头开始排序。

问题

使用 flex 布局,设置justify-content: space-between,会让一行空间评分,但是最后一行不到 2 个时,会出现空白的情况,不会从头对齐。如何让最后一行从头对齐呢?

使用空的 div 占位,让最后一行 div 元素数量为 3 个,这样就可以从头对齐了。

html
<script setup>
import DescItem from './DescItem.vue'
import EmptyItem from './EmptyItem.vue'

const props = defineProps({
  descList: {
    type: Array,
    default: () => [
      /*
      {
        label: '部门名称',
        value: '市场部',
      },
      {
        label: '部门负责人',
        value: '张三',
      },
      {
        label: '联系电话',
        value: '13888888888',
      },
      {
        label: '传真',
        value: '010-88888888',
      },
      {
        label: '邮箱',
        value: '',
      },
      */
    ],
  },
  data: {
    type: Object,
    default: () => {
      return {}
    },
  },
})

const emptySize = computed(() => {
  // 余数 1 -- 最后一行为 2 个。余数 2 -- 最后一行为 1 个,补齐两个空的
  const remainder = props.descList.length % 3
  if (remainder === 2) return 2
  return 0
})
</script>

<template>
  <div class="sy-component desc-info">
    <DescItem
      v-for="(item, index) in descList"
      :key="index"
      :label="item.label"
      :value="data?.[item.prop]" />
    <EmptyItem v-for="index in emptySize" :key="index" />
  </div>
</template>

<style lang="scss">
.sy-component.desc-info {
  display: flex;
  flex-flow: row wrap;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 20px;
}
</style>

参考:

让 CSS flex 布局最后一行列表左对齐的 N 种方法

flex 布局——既平分又可换行布局

hex-8 颜色值格式

常见的颜色值格式有:

  • #fff —— 3 位 简写的 hex 颜色值
  • #ffffff —— 6 位 不简写的 hex 颜色值
  • #ffffff99 —— hex-8 颜色值 最前面的两位表示透明度 99 表示 60% 的透明度 00 表示完全透明 FF 表示完全不透明
  • rgb(255, 255, 255) —— rgb 颜色值
  • rgba(255, 255, 255, 1) —— rgba 颜色值
  • hsl(0, 0%, 100%) —— hsl 颜色值
  • hsla(0, 0%, 100%, 1) —— hsla 颜色值

如何设置 hex-8 的透明度呢?

查看透明度关系表

flex 布局元素撑满剩余高度

html
<div class="father">
  <div class="child-1">高度不定</div>
  <div class="child-2">希望占满父元素剩余高度</div>
</div>

<style>
.father {
  display: flex;
  flex-flow: column nowrap;
}
.child-2 {
  flex: 1;
  min-height: 0;/* NOTE 当子元素设置了 flex: 1 时,如果子元素内容超出父元素高度,子元素会撑开父元素,这时候需要设置 min-height: 0,否则子元素不会撑开父元素 */
  min-width: 0; /* 同上,保证有滚动条 */
}
</style>

深入学习

写给自己看的 display: flex 布局教程

Released under the MIT License.