지역 변수
Coddy HTML 여정의 실전 프론트엔드 섹션에 포함된 레슨. 35개 중 4번째.
변수를 선언할 때 :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 플레이그라운드