Modern CSS
Custom properties, nesting, container queries, and modern selectors.
Overview
Modern CSS provides powerful features for styling web pages.
Key Concepts
- Custom Properties — CSS variables for reusable values
- Nesting — Write nested CSS rules
- Container Queries — Style based on parent size
- :has() Selector — Parent selector
- Logical Properties — Bidirectional layouts
Code Examples
/* Custom properties */
:root {
--primary: #007bff;
--secondary: #6c757d;
--spacing-unit: 8px;
--font-family: system-ui, -apple-system, sans-serif;
}
.button {
background: var(--primary);
padding: calc(var(--spacing-unit) * 2) calc(var(--spacing-unit) * 3);
font-family: var(--font-family);
}
/* Nesting */
.card {
background: white;
border-radius: 8px;
& .title {
font-size: 1.5rem;
font-weight: bold;
&:hover {
color: var(--primary);
}
}
& .content {
color: #666;
line-height: 1.6;
}
&:hover {
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}
}
/* Container queries */
.widget-container {
container-type: inline-size;
container-name: widget;
}
@container widget (min-width: 400px) {
.widget {
display: flex;
gap: 1rem;
}
}
/* :has() selector */
.form-group:has(:invalid) {
border-color: red;
}
.form-group:has(:focus) {
border-color: var(--primary);
}
/* Logical properties */
.element {
margin-inline: auto;
padding-block: 1rem;
border-inline-start: 4px solid var(--primary);
text-align: start;
}
/* Clamp for responsive sizing */
h1 {
font-size: clamp(1.5rem, 4vw, 3rem);
}
/* :is() and :where() selectors */
:is(h1, h2, h3) {
font-weight: bold;
line-height: 1.2;
}
:where(.button, .link) {
cursor: pointer;
}
Practice
Refactor CSS to use custom properties and modern selectors.