gnosis23 / hello-world-blog

还是 issues 里面写文章方便
https://bohao.work
0 stars 0 forks source link

提升css开发效率 #88

Open gnosis23 opened 2 years ago

gnosis23 commented 2 years ago

直接写 css 效率不高,比如调整 margin padding 这些,或者改改元素左右对齐放置,我需要这样写

<div style={{ marginTop: 2, padding: 2 }}>
  <span>content</span>
</div>

一般 react 组件中如果使用 css modules 的话,需要这么写

// a.html
<div className={style.myCustomCls}>
  <span>content</span>
</div>

// style.css
.myCustomCls {
  padding: 2px;
  margin-top: 2px;
}

可以看到我只是想要稍微加点属性,犯不着写这么多的代码吧。这些基本场景应该用 mixin 或者 预先定义好的 class 来解决。

调研下:

gnosis23 commented 2 years ago

tailwind

推荐指数:⭐⭐⭐⭐

想要直接把 tailwind 用在已有的项目里是比较难的,原因如下:

mixin

但是把一部分 class 换成 mixin 是可行的,比如

space-x-4 可以换成

.space-x(@gap) {
  & > not([hidden]) ~ not([hidden]) {
    margin-left: @gap;
  }
}

使用的时候只要如下即可

.child {
  .space-x(6px);
}

再比如 flex-col可以写成

.flex-col() {
  display: flex;
  flex-direction: column;
}

预设部分class

使用 sass 的循环功能来预定义一些标签

// 抄袭tailwind
@for $i from 1 through 12 {
  .p-#{$i} {
    padding: #{$i};
  }
  .pt-#{$i} {
    padding-top: #{$i};
  }
  .pl-#{$i} {
    padding-left: #{$i};
  }
  .pr-#{$i} {
    padding-right: #{$i};
  }
  .pb-#{$i} {
    padding-bottom: #{$i};
  }
  .px-#{$i} {
    padding-left: #{$i};
    padding-right: #{$i};
  }
  .py-#{$i} {
    padding-top: #{$i};
    padding-bottom: #{$i};
  }

  .m-#{$i} {
    margin: #{$i}px;
  }
  .mt-#{$i} {
    margin-top: #{$i}px;
  }
  .ml-#{$i} {
    margin-left: #{$i}px;
  }
  .mr-#{$i} {
    margin-right: #{$i}px;
  }
  .mb-#{$i} {
    margin-bottom: #{$i}px;
  }
  .mx-#{$i} {
    margin-left: #{$i}px;
    margin-right: #{$i}px;
  }
  .my-#{$i} {
    margin-top: #{$i}px;
    margin-bottom: #{$i}px;
  }

  .space-x-#{$i} > not([hidden]) ~ not([hidden]) {
    margin-left: #{$i}px;
  }
  .space-y-#{$i} > not([hidden]) ~ not([hidden]) {
    margin-top: #{$i}px;
  }
}

.flex {
  display: flex;
}
.flex-column {
  display: flex;
  flex-direction: column;
}
.flex-wrap {
  flex-wrap: wrap;
}
// 不考虑初始尺寸
.flex-1 {
  flex: 1 1 0;
}
.flex-auto {
  flex: 1 1 auto;
}
.flex-none {
  flex: 0 0 auto;
}
.justify-between {
  justify-content: space-between;
}
.justify-center {
  justify-content: center;
}
.items-center {
  align-items: center;
}
.items-end {
  align-items: flex-end;
}
.items-baseline {
  align-items: baseline;
}
gnosis23 commented 2 years ago

styled-jsx

推荐指数:⭐⭐

用起来是这种感觉

    <div>
      <p>Only this paragraph will get the style :)</p>

      <Paragraph />

      <style jsx>{`
        p {
          color: red;
        }
      `}</style>
    </div>

比直接写 css 是方便那么点点... 但是好像不支持嵌套啊

gnosis23 commented 2 years ago

styled-component

看了下文档,比想象中更强大,可以实际操作下。

gnosis23 commented 2 years ago

vanilla-extract

推荐指数:⭐⭐⭐⭐

先看看 https://css-tricks.com/css-in-typescript-with-vanilla-extract/ ,有什么优点: