المتغيرات المحلية
جزء من قسم الواجهة الأمامية العملية في رحلة HTML على Coddy. الدرس 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>يتضمن هذا الدرس اختبارًا قصيرًا. ابدأ الدرس للإجابة عليه وتتبّع تقدمك.
جميع دروس الواجهة الأمامية العملية
تدرّب بنفسك: Playground لـ Web