第六届字节跳动青训营第三课 | CSS的一些不常见内容补充

77 阅读6分钟

1、自定义属性

  1. CSS自定义属性的类型

CSS自定义属性本质上可以存储任何有效的CSS值。这包括但不限于:

  • 颜色值(如 #ff0000, rgb(255, 0, 0), hsl(0, 100%, 50%)
  • 长度单位(如 10px, 2em, 5rem, 50%
  • 字符串(如 'Helvetica', 'sans-serif'
  • 数字(如 1, 2.5
  • 角度(如 45deg, 1turn
  • 时间(如 300ms, 2s
  • 函数值(如 calc(), var()
  • 关键字(如 center, bold
  1. 语法和用法

定义自定义属性:

:root {
  --main-color: #ff0000;
  --font-size: 16px;
}

使用自定义属性:

.element {
  color: var(--main-color);
  font-size: var(--font-size);
}

你也可以提供一个后备值:

.element {
  font-size: var(--font-size, 14px);
}
  1. 作用域和继承

CSS自定义属性遵循CSS的级联规则和继承机制。

  • 全局作用域:通常在:root选择器中定义
  • 局部作用域:可以在任何选择器中定义和重写
  • 继承:子元素会继承父元素的自定义属性

例如:

:root {
  --main-color: blue;
}

.parent {
  --main-color: green;
}

.child {
  color: var(--main-color); /* 这里的颜色是绿色 */
}
  1. 常见使用场景

a. 主题切换

import { useState } from 'react'
import { Button } from "@/components/ui/button"

export default function Component() {
  const [theme, setTheme] = useState('light')

  const toggleTheme = () => {
    document.documentElement.setAttribute('data-theme', theme === 'light' ? 'dark' : 'light')
    setTheme(theme === 'light' ? 'dark' : 'light')
  }

  return (
    <div className="p-4">
      <h1 className="text-2xl font-bold mb-4">Theme Switcher</h1>
      <p className="mb-4">Current theme: {theme}</p>
      <Button onClick={toggleTheme}>Toggle Theme</Button>
    </div>
  )
}

相应的CSS:

:root {
  --bg-color: white;
  --text-color: black;
}

[data-theme="dark"] {
  --bg-color: black;
  --text-color: white;
}

body {
  background-color: var(--bg-color);
  color: var(--text-color);
}

b. 响应式设计

:root {
  --container-width: 1200px;
}

@media (max-width: 1200px) {
  :root {
    --container-width: 992px;
  }
}

@media (max-width: 992px) {
  :root {
    --container-width: 768px;
  }
}

.container {
  max-width: var(--container-width);
}

c. 组件样式变体

.button {
  --button-color: blue;
  background-color: var(--button-color);
}

.button.danger {
  --button-color: red;
}
  1. 高级技巧

a. 使用calc()和自定义属性

:root {
  --spacing-unit: 8px;
}

.element {
  padding: calc(var(--spacing-unit) * 2);
  margin-bottom: calc(var(--spacing-unit) * 3);
}

b. 在JavaScript中操作自定义属性

// 设置自定义属性
document.documentElement.style.setProperty('--main-color', 'blue');

// 获取自定义属性
const mainColor = getComputedStyle(document.documentElement).getPropertyValue('--main-color');

c. 嵌套自定义属性

:root {
  --base-color: #ff0000;
  --main-color: var(--base-color);
}

2、对于var()

var() 是CSS中用于插入自定义属性(也称为CSS变量)值的函数。它允许你在样式表中使用预先定义的变量,从而使CSS更加灵活和可维护。让我详细解释一下:

  1. 基本语法
var(--custom-property-name, optional-fallback-value)
  • --custom-property-name 是你定义的自定义属性名称。
  • optional-fallback-value 是可选的后备值,如果自定义属性未定义或无效,则使用此值。
  1. 使用方法

首先,你需要定义一个自定义属性:

:root {
  --main-color: #007bff;
}

然后,你可以在样式中使用 var() 函数来引用这个自定义属性:

.button {
  background-color: var(--main-color);
}
  1. 实际例子
import { useState } from 'react'
import { Button } from "@/components/ui/button"

export default function Component() {
  const [color, setColor] = useState('#007bff')

  const changeColor = () => {
    const newColor = '#' + Math.floor(Math.random()*16777215).toString(16)
    document.documentElement.style.setProperty('--main-color', newColor)
    setColor(newColor)
  }

  return (
    <div className="p-4 space-y-4">
      <style jsx global>{`
        :root {
          --main-color: ${color};
        }
        .custom-button {
          background-color: var(--main-color);
          color: white;
          padding: 10px 20px;
          border-radius: 5px;
          border: none;
          cursor: pointer;
        }
        .color-display {
          color: var(--main-color);
        }
      `}</style>
      <h1 className="text-2xl font-bold">var() Function Demo</h1>
      <p className="color-display font-semibold">
        Current main color: {color}
      </p>
      <button className="custom-button">
        Button using var(--main-color)
      </button>
      <div>
        <Button onClick={changeColor}>Change Color</Button>
      </div>
    </div>
  )
}

在这个例子中:

  1. 我们定义了一个自定义属性 --main-color
  2. 我们使用 var(--main-color) 来设置按钮的背景色和文本的颜色。
  3. 我们提供了一个按钮来随机改变 --main-color 的值,展示了 var() 的动态特性。
  4. var() 的优势
  • 可维护性:你可以在一个地方定义颜色、尺寸等,然后在整个样式表中重复使用。
  • 主题化:轻松创建和切换主题。
  • 响应式设计:可以根据媒体查询改变变量值,简化响应式样式。
  • 继承:自定义属性遵循CSS的继承规则,可以在DOM树中向下传递。
  1. 注意事项
  • 浏览器支持:现代浏览器都支持 var(),但IE11及以下版本不支持。
  • 性能:过度使用可能会略微影响性能,但通常影响很小。
  • 回退值:始终提供一个回退值是个好习惯,以确保在变量未定义时样式仍然有效。

3、实体(& )

HTML实体是在HTML中表示特殊字符的一种方式。以下是一些最常用的HTML实体

  1. &lt; - 小于号 (<)
  2. &gt; - 大于号 (>)
  3. &amp; - 和号 (&)
  4. &quot; - 双引号 (")
  5. &apos; - 单引号 (')
  6. &nbsp; - 不间断空格
  7. &copy; - 版权符号 (©)
  8. &reg; - 注册商标 (®)
  9. &trade; - 商标 (™)
  10. &euro; - 欧元符号 (€)
  11. &pound; - 英镑符号 (£)
  12. &yen; - 日元符号 (¥)
  13. &deg; - 度数符号 (°)
  14. &plusmn; - 加减号 (±)
  15. &times; - 乘号 (×)
  16. &divide; - 除号 (÷)
  17. &frac12; - 二分之一 (½)
  18. &larr; - 左箭头 (←)
  19. &rarr; - 右箭头 (→)
  20. &uarr; - 上箭头 (↑)
  21. &darr; - 下箭头 (↓)

使用HTML实体的一些注意事项:

  1. 在HTML中,某些字符(如 <, >, &)有特殊含义。使用它们的实体可以避免解析错误。
  2. 在显示代码示例时,使用实体可以确保代码正确显示而不被浏览器解释为HTML。
  3. 某些特殊字符(如版权符号、商标符号等)在不同的字符编码中可能显示不正确,使用实体可以确保它们在所有环境中正确显示。
  4. 在React或其他现代前端框架中,通常不需要手动使用HTML实体,因为这些框架会自动转义特殊字符。

4、calc()函数

calc() 是CSS中的一个强大函数,它允许你在CSS中进行数学计算。这个函数可以在设置CSS属性值时执行基本的数学运算,使得样式更加灵活和动态。 以下是关于 calc() 的一些重要信息:

  1. 基本语法:
property: calc(expression);

其中 expression 是一个数学表达式。 2. 支持的运算:

  1. 加法 (+)

  2. 减法 (-)

  3. 乘法 (*)

  4. 除法 (/)

  5. 特点:

  6. 可以混合不同的单位(如px和%)

  7. 运算符前后必须有空格

  8. 可以嵌套使用

  9. 常见用途:

  10. 响应式布局

  11. 动态计算尺寸

  12. 居中元素

  13. 创建灵活的网格系统

让我们通过一个React组件来展示 calc() 的实际应用: ![[Pasted image 20241102003400.png]] ![[Pasted image 20241102003411.png]]

这个组件展示了 calc() 的几个用例:

  1. 动态调整布局:主内容区的宽度使用 calc() 根据侧边栏宽度动态计算。
  2. 混合单位:展示了如何在 calc() 中混合使用像素和百分比。
  3. 响应式设计:展示了如何使用 calc() 结合视口单位(vw)创建响应式元素。

calc() 函数的一些重要应用场景:

  1. 创建灵活的布局:
.container {
  width: calc(100% - 40px);
  margin: 0 20px;
}
  1. 居中元素:
.center-element {
  position: absolute;
  left: calc(50% - 50px); /* 假设元素宽度为100px */
}
  1. 响应式字体大小:
body {
  font-size: calc(14px + 0.5vw);
}
  1. 创建网格系统:
.grid-item {
  width: calc((100% - 20px) / 3); /* 3列网格,间隔10px */
  margin-right: 10px;
}

注意事项:

  • 浏览器支持:现代浏览器都支持 calc(),但IE9及以下版本不支持。
  • 性能:过度复杂的 calc() 表达式可能会影响性能,尤其是在频繁重新计算的情况下。
  • 单位兼容性:确保在进行计算时使用兼容的单位。