9. Advanced CSS
CSS Variables (Custom Properties)
CSS Variables allow you to store reusable values and maintain consistency across your stylesheets. You can define variables globally or scoped to a specific selector.
/* Declaring variables */
:root {
--primary-color: #3498db;
--secondary-color: #2ecc71;
--card-padding: 20px;
}
/* Using variables */
div.card {
background-color: var(--primary-color);
padding: var(--card-padding);
border: 2px solid var(--secondary-color);
}
/* Fallback value */
div.alert {
color: var(--alert-color, red); /* uses red if --alert-color is not defined */
}Variables can be scoped to a specific element, meaning their values only apply within that element’s subtree.
Pseudo-Classes & Pseudo-Elements
Pseudo-classes let you style elements based on their state, position, or relation to other elements, while pseudo-elements let you style parts of an element or insert content.
/* Pseudo-classes */
a:hover {
color: #e74c3c;
}
input:focus {
outline: 2px solid #3498db;
}
ul li:nth-child(odd) {
background-color: #f0f0f0;
}
p:first-of-type {
font-weight: bold;
}
/* Pseudo-elements */
p::before {
content: '🔥 ';
}
p::after {
content: ' ✨';
}
::selection {
background-color: #2ecc71;
color: white;
}Using pseudo-classes and pseudo-elements together lets you create interactive and dynamic effects without extra HTML elements.
CSS Functions
CSS functions allow you to calculate values dynamically or manipulate colors, URLs, and custom properties. They help make your layout responsive and maintainable.
/* calc() for dynamic sizing */
div.container {
width: calc(100% - 40px);
padding: 20px;
}
/* min(), max(), clamp() */
div.box {
width: clamp(200px, 50%, 400px); /* min 200px, preferred 50%, max 400px */
}
/* Using variables */
div.card {
border-color: var(--primary-color);
}
/* Color functions */
div.highlight {
background-color: rgb(52, 152, 219);
color: hsl(200, 80%, 50%);
}Mini Project Step
Create a themed card layout using CSS variables for colors, padding, and border-radius. Add hover effects using pseudo-classes, and insert icons before and after headings using pseudo-elements. Use calc() and clamp() to make the card responsive across screen sizes.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Advanced CSS Card</title>
<style>
:root {
--primary-color: #3498db;
--secondary-color: #2ecc71;
--padding: 20px;
--radius: 10px;
}
.card {
background-color: var(--primary-color);
padding: var(--padding);
border-radius: var(--radius);
width: clamp(200px, 50%, 400px);
color: white;
text-align: center;
transition: all 0.3s ease;
}
.card:hover {
background-color: var(--secondary-color);
transform: scale(1.05);
}
.card h2::before {
content: '✨ ';
}
.card h2::after {
content: ' 🔥';
}
</style>
</head>
<body>
<div class="card">
<h2>Advanced CSS Card</h2>
<p>Hover to see pseudo-class and pseudo-element effects!</p>
</div>
</body>
</html>