Menu
CoddyTech

局部变量

本课属于 Coddy HTML 学习旅程的“前端实践”单元。第 4 课,共 35 课。

你可能已经注意到,我们经常使用 :root 来声明变量。这是因为 :root 是全局的:在这里定义的变量适用于整个 HTML 页面(正如我们之前提到的)。

但有时,你希望变量只影响页面的某些部分。例如,想象一下,你正在搭建一个有许多商品卡片的在线商店。你可以在 .card 类中创建变量,只为这些卡片设置样式,而不影响其他元素。

.card {
  --card-color: orchid;
  background-color: var(--card-color);
}

这样,变量只会在 .card 元素内部生效,让你能更好地控制特定区域。

challenge icon

挑战

简单

你会看到一个包含多张商品卡片的网店页面。你的任务:

  1. 在 .card 类中,创建一个名为 --card-accent 的局部 CSS 变量,并将其值设为 coral。
  2. 使用这个变量设置卡片内 <h3> 标题的文字颜色。
  3. 使用同一个变量设置卡片 <button> 的背景颜色。

亲手试试

<html>
<head>
    <title>Local Variables</title>
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Playfair+Display:ital,wght@0,400..900;1,400..900&display=swap" rel="stylesheet">    <style>
      /* Global variable for body background */
      :root {
        --body-bg: #000f26;
        --font-family: "Playfair Display", serif;
      }
    
      body {
        background-color: var(--body-bg);
        font-family: var(--font-family);
        padding: 20px;
        display: flex;
        gap: 20px;
        justify-content: center;
      }
    
      /* Card styles */
      .card {
        --card-bg: white;
        background-color: var(--card-bg);
        border-radius: 10px;
        padding: 15px;
        width: 250px;
        text-align: center;
        box-shadow: 0 4px 8px rgba(0,0,0,0.1);
      }
    
      .card h3 {
        margin-top: 0;
      }
    
      .card p {
        font-size: 0.9rem;
        color: #333;
      }
    
      .card button {
        border: none;
        color: #000f26;
        padding: 8px 12px;
        border-radius: 5px;
        cursor: pointer;
        font-weight: bold;
        margin-top: 10px;
        width: 100%;
      }
    
    </style>
    </head>
    <body>
    
    <div class="card">
      <h3>Classic Sneakers</h3>
      <p>Comfortable and stylish sneakers for everyday wear.</p>
      <button>Buy Now</button>
    </div>
    
    <div class="card special">
      <h3>Luxury Watch</h3>
      <p>Elegant watch with a unique design for special occasions.</p>
      <button>Buy Now</button>
    </div>
    
    <div class="card">
      <h3>Leather Backpack</h3>
      <p>Durable, spacious backpack made from premium leather.</p>
      <button>Buy Now</button>
    </div>
    
    </body>
</html>
quiz icon自我测试

这节课包含一个小测验。开始学习即可作答,并记录你的进度。

前端实践中的所有课

自己练习: Web 在线编辑器