Advanced CSS Features
Advanced CSS Features
CSS Variables help you store values and reuse them throughout your CSS, making your styles easier to manage and update. Let’s make this interactive with step-by-step exercises!
First, let’s define and use a variable.
In your CSS file (style.css):
:root {
--main-color: #3498db; /* A nice blue */
--text-color: white;
--font-size: 18px;
}
body {
background-color: var(--main-color);
color: var(--text-color);
font-size: var(--font-size);
text-align: center;
padding: 20px;
}
In your HTML file (index.html):
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CSS Variables</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<h1>Hello, CSS Variables! 🎨</h1>
</body>
</html>
What happens?
The background turns blue (-main-color).
The text is white (-text-color).
The font size is 18px (-font-size).
Try It: Change --main-color in CSS to red. What happens?
Step 2: Use CSS Variables in Buttons
Let’s make a button that uses the same colors.
🔹 Add this to your style.css:
button {
background-color: var(--main-color);
color: var(--text-color);
padding: 10px 20px;
border: none;
font-size: var(--font-size);
cursor: pointer;
border-radius: 5px;
}
🔹 Add this inside <body> in index.html:
<button>Click Me</button>
What happens?
The button background is blue (-main-color).
The text is white (-text-color).
Try It: Change --main-color in CSS to #e74c3c (red). Does the button change color too?
Step 3: Overriding Variables in Specific Sections
Sometimes, you want different colors in different sections. Let’s override our variables inside a .card class.
🔹 Add this to style.css:
.card {
--main-color: #e74c3c; /* Change blue to red */
background-color: var(--main-color);
padding: 20px;
border-radius: 10px;
text-align: center;
}
🔹 Add this inside <body> in index.html:
<div class="card"> <h2>I'm a Card!</h2> </div>
What happens?
.card will have a red background instead of blue!
✅ Try It: Change --main-color inside .card to green. What happens?
Step 4: Fallback Values
If a variable is not defined, we can provide a default value.
🔹 Example (style.css):
h1 { color: var(--title-color, black); /* Uses black if --title-color is missing */ }
What happens?
Since -title-color is not defined, the heading will be black!
✅ Try It: Define --title-color in :root and change it to purple. Does the heading color change?
Your Challenge: Create a Dark Mode!
1️⃣ Define --bg-color and --text-color in :root.
2️⃣ Create two classes:
.light-mode (light background, dark text)
.dark-mode (dark background, light text)
3️⃣ Apply the class in your HTML <body> and see the difference!
Implementing Dark Mode in CSS
Dark mode is a popular UI feature that provides a darker color scheme to reduce eye strain, save battery life, and enhance the overall user experience. Let’s make this interactive by exploring different ways to implement dark mode using CSS and JavaScript!
Method 1: CSS Only (Using prefers-color-scheme)
If you want to apply dark mode automatically based on the user's system settings, CSS provides a built-in media query called prefers-color-scheme.
/* Default (Light Mode) */
body {
background-color: white;
color: black;
}
/* Dark Mode (If user has enabled dark mode in system settings) */
@media (prefers-color-scheme: dark) {
body {
background-color: black;
color: white;
}
}
How it works:
If the user’s device is set to dark mode, the styles inside @media (prefers-color-scheme: dark) will apply automatically.
✅ Pros: No JavaScript needed, works automatically.
❌ Cons: No manual toggle option for users.
Method 2: Toggle Dark Mode with a Button (CSS + JavaScript)
To manually switch between light and dark mode, we can use CSS Variables and JavaScript.
:root {
--bg-color: white;
--text-color: black;
}
/* Dark Mode */
.dark-mode {
--bg-color: black;
--text-color: white;
}
/* Apply variables */
body {
background-color: var(--bg-color);
color: var(--text-color);
transition: 0.3s ease-in-out;
}
/* Button Style */
button {
padding: 10px 20px;
background-color: var(--text-color);
color: var(--bg-color);
border: none;
cursor: pointer;
}
Step 2: Add HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Dark Mode Toggle</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<h1>Dark Mode Example 🌙</h1>
<button onclick="toggleDarkMode()">Toggle Dark Mode</button>
<script>
function toggleDarkMode() {
document.body.classList.toggle('dark-mode');
}
</script>
</body>
</html>
How it works:
The dark-mode class is added or removed when the button is clicked.
CSS Variables change colors dynamically.
✅ Pros: Users can toggle manually.
❌ Cons: Does not remember user preference after a page refresh.
Method 3: Save Dark Mode Preference (Local Storage)
To remember the user’s choice, we can use local storage in JavaScript.
🔹 Updated JavaScript
function toggleDarkMode() {
document.body.classList.toggle('dark-mode');
// Save the user’s choice in local storage
if (document.body.classList.contains('dark-mode')) {
localStorage.setItem('theme', 'dark');
} else {
localStorage.setItem('theme', 'light');
}
}
// Check user preference on page load
window.onload = function () {
if (localStorage.getItem('theme') === 'dark') {
document.body.classList.add('dark-mode');
}
};
How it works:
The user’s choice is saved in localStorage.
The preference is applied automatically when the page reloads.
✅ Pros: Saves user preference, works after a refresh.
❌ Cons: Needs JavaScript.
Summary
CSS Functions (calc(), min(), max(), clamp()) Explained with Examples!
CSS functions like calc(), min(), max(), and clamp() allow us to create dynamic, flexible layouts without relying on JavaScript. Let’s make this interactive with examples! 🎨
calc() allows you to add, subtract, multiply, or divide values directly inside CSS properties.
.box {
width: calc(100% - 50px);
background: lightblue;
padding: 20px;
}
Why use calc()?
Combines different units (%, px, em, rem).
Great for responsive layouts.
Try It Yourself! Change 50px to 30px and see how the width changes!
min(value1, value2, value3, ...) selects the smallest value among given options.
Example: Responsive Box
.box { width: min(50vw, 400px);
background: lightgreen;
padding: 20px; }
Why use min()?
✅ Ensures an element never gets too big.
✅ Ideal for responsive layouts where you want to limit width.
🎯 Try It Yourself! Resize the window and watch how the width adjusts dynamically!
max(value1, value2, value3, ...) selects the largest value among given options.
.box { width: max(300px, 50vw);
background: lightcoral;
padding: 20px; }
🔹 Why use max()?
✅ Ensures an element never gets too small.
✅ Great for maintaining readability on small screens.
🎯 Try It Yourself! Shrink the window to see how it keeps a minimum size!
clamp(min, preferred, max) keeps a value between a minimum and a maximum while favoring the preferred value.
p { font-size: clamp(16px, 2vw, 32px); }
How it works:
The font size is at least 16px.
It scales based on 2vw (2% of viewport width).
It never exceeds 32px.
🔹 Why use clamp()?
✅ Perfect for fluid typography.
✅ Ensures text remains readable on all devices.
🎯 Try It Yourself! Resize your browser and watch the font size adjust dynamically!
Summary: When to Use Each Function?