Skip to content

css in js

介绍

css in js 的核心思想是:用一个 JS 对象来描述样式,而不是 css 样式表

例如下面的对象就是一个用于描述样式的对象:

js
const styles = {
  backgroundColor: "#f40",
  color: "#fff",
  width: "400px",
  height: "500px",
  margin: "0 auto",
};

由于这种描述样式的方式根本就不存在类名,自然不会有类名冲突

至于如何把样式应用到界面上,不是它所关心的事情,你可以用任何技术、任何框架、任何方式将它应用到界面。

后续学习的 vue、react 都支持 css in js,可以非常轻松的应用到界面

css in js 的特点:

  • 绝无冲突的可能:由于它根本不存在类名,所以绝不可能出现类名冲突
  • 更加灵活:可以充分利用 JS 语言灵活的特点,用各种招式来处理样式
  • 应用面更广:只要支持 js 语言,就可以支持 css in js,因此,在一些用 JS 语言开发移动端应用的时候非常好用,因为移动端应用很有可能并不支持 css
  • 书写不便:书写样式,特别是公共样式的时候,处理起来不是很方便
  • 在页面中增加了大量冗余内容:在页面中处理 css in js 时,往往是将样式加入到元素的 style 属性中,会大量增加元素的内联样式,并且可能会有大量重复,不易阅读最终的页面代码

实践

1.不存在类名冲突

html
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>

  <body>
    <div id="box1"></div>
    <div id="box2"></div>
  </body>
  <script src="./scripts/index.js" type="module"></script>
</html>
js
import { applyStyles } from "./apply.js";

const style = {
  width: "500px",
  height: "500px",
  backgroundColor: "#f55",
  color: "#fff",
  border: "2px solid #333",
  margin: "0 auto",
};

const box1 = document.querySelector("#box1");
const box2 = document.querySelector("#box2");

applyStyles(box1, style); //将style应用到页面dom
applyStyles(box2, style);
js
/**
 * 将样式应用到页面
 * @param {*} dom   dom元素
 * @param {*} styles 样式对象
 */
export function applyStyles(dom, styles) {
  for (const key in styles) {
    const value = styles[key];
    dom.style[key] = value;
  }
}

2.再看一下 css in js 的灵活性

主要是对 apply.js 进行了更改

js
/**
 * 将样式应用到页面
 * @param {*} dom   dom元素
 * @param {*} styles 样式对象
 */
export function applyStyles(dom, ...styles) {
  let resStyles = {}; //最终合并的对象
  //合并一下属性,剩余运算符保证函数可以传入多个参数
  for (const style of styles) {
    resStyles = { ...resStyles, ...style };
  }

  for (const key in resStyles) {
    const value = resStyles[key];
    dom.style[key] = value;
  }
}
js
// 公共样式,对公共的样式进行抽离
export const redBG = {
  backgroundColor: "#f55",
};

// 可以将样式写成函数,更加灵活
export const border = (width = 2, color = "#ebeef5") => {
  return {
    border: `${width}px solid ${color}`,
  };
};
js
import { applyStyles } from "./apply.js";
import { border, redBG } from "./common.js";

const style = {
  width: "500px",
  height: "500px",
  color: "#fff",
  margin: "0 auto",
};

const box1 = document.querySelector("#box1");
const box2 = document.querySelector("#box2");

applyStyles(box1, style, redBG, border(1, "#333")); //使用样式,添加到dom
applyStyles(box2, style, redBG, border());

css in js 在移动端的应用更加广泛,跨平台也更方便,我们不需要关注怎么将样式应用到页面,那是由平台框架所提供的。

在 PC 样式是 css,而在移动端就不一样了,各有差异

MIT License