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