ローカル変数
CoddyのHTMLジャーニー「実践的フロントエンド」セクションの一部。レッスン 4/35。
変数を宣言するために、よく:rootを使うことに気づいたかもしれません。これは、:rootがグローバルだからです。ここで定義した変数は、HTMLページ全体に適用されます(前に説明したとおりです)。
ただし、ページの特定の部分にだけ影響する変数を使いたい場合もあります。たとえば、多数の商品カードがあるオンラインショップを作るとします。.cardクラスの中に変数を作成すれば、ほかの要素に影響を与えずに、そのカードだけのスタイルを設定できます。
.card {
--card-color: orchid;
background-color: var(--card-color);
}この方法では、変数は.card要素の内部でのみ機能するため、特定の領域をより細かく制御できます。
チャレンジ
簡単いくつかの商品カードがあるオンラインショップのページが用意されています。課題:
.cardクラス内に、ローカルCSS変数--card-accentを作成し、その値をcoralに設定してください。- この変数を使って、カード内の見出し
<h3>のテキストの色を設定してください。 - 同じ変数を使って、カードの
<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>このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。
実践的フロントエンドのすべてのレッスン
自分で練習してみよう: Webプレイグラウンド