开发一个常用的响应式 css 工具类

908 阅读2分钟

经常就遇到有人说,用 Vue 做一个响应式的网站,用 Bootstrap 呢,还是用 Element-ui 或者 Ant Design Vue 还是其他的组件库。当然用 Vuetify 挺好的,但是有时候我们或者老板们不喜欢 Material Design 的设计。而且说实在的, Vuetify 的文档以及有些组件的设计让我觉得我比较笨(可能确实是人比较笨)。

所以写一套我们需要的一个响应式 css 工具类,至少能让我们开发一个响应式网站要方便快捷很多,并且想用什么组件库就用好了。

1. 确定断点

我们就用 Bootstrap 的响应式断点为例吧,至少 Ant Design Vue 的栅格系统默认也是用的这个。

定义 breakpoints 变量:

@breakpoints: {
  xs: 0px; // 为了方便,就设为最小为 0px
  sm: 576px;
  md: 768px;
  lg: 992px;
  xl: 1200px;
  xxl: 1600px;
};

因为我们需要用到 keyvalue,所以breakpoints为一个 map类型。

2. 创建一个 mixin 函数

.breakpoints-properties(@prefix, @properties, @value) {
  .@{prefix}@{value} {
    @{properties}: @value;
  }
  each(@breakpoints, .(@v, @k, @i){
    .@{prefix}@{k}-@{value} {
      @media (min-width: @v) {
        @{properties}: @value !important;
      }
    }
  });
};
  • @prefix 为 class 的前缀
  • @value 为属性具体的值
  • @properties 为属性

3. 定义属性-值的映射关系表

@properties: {
  @display: {
    @key: display;
    @values: block, inline, inline-block, none, flex, inline-flex, table, table-cell, table-row;
    @prefix: d-;
  };
  @flex-direction: {
    @key: flex-direction;
    @values: row, row-reverse, column, column-reverse;
    @prefix: direction-;
  };
  @flex-wrap: {
    @key: flex-wrap;
    @values: nowrap, wrap, wrap-reverse;
    @prefix: wrap-;
  };
  @justify-content: {
    @key: justify-content;
    @values: flex-start, flex-end, center, space-between, space-around;
    @prefix: justify-;
  };
  @align-items: {
    @key: align-items;
    @values: flex-start, flex-end, center, baseline, stretch;
    @prefix: align-;
  };
  @order: {
    @key: order;
    @values: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14;
    @prefix: order-;
  };
  @flex-grow: {
    @key: flex-grow;
    @values: 0, 1;
    @prefix: grow-;
  };
  @flex-shrink: {
    @key: flex-shrink;
    @values: 0, 1;
    @prefix: shrink-;
  };
  @flex: {
    @key: flex;
    @values: auto, 1, none;
    @prefix: flex-;
  };
  @align-self: {
    @key: align-self;
    @values: flex-start, flex-end, center, baseline, stretch;
    @prefix: align-self-;
  };
  @float: {
    @key: float;
    @values: left, right, none;
    @prefix: float-;
  };
  @text-align: {
    @key: text-align;
    @values: left, center, right;
    @prefix: text-;
  };
  @font-weight: {
    @key: font-weight;
    @values: 400, 500, 700, 900;
    @prefix: font-;
  };
  @font-style: {
    @key: font-style;
    @values: normal, italic, oblique;
    @prefix: font-;
  };
  @text-decoration: {
    @key: text-decoration;
    @values: none, overline, underline, line-through;
    @prefix: text-decoration-;
  };
  @text-transform: {
    @key: text-transform;
    @values: uppercase, lowercase, capitalize;
    @prefix: text-;
  };
};

4. 遍历生成

each(@properties, {
  each(@value[@values], .(@v, @k, @i){
    .breakpoints-properties(@value[@prefix], @value[@key], @v);
  });
});

当然这些其实还远远不够,还有文字截断、间距... 也有些属性我们不需要的可以删除掉。

最终代码可以参考 @convue-lib/styles

文档地址:ziping-li.github.io/convue-lib/…