CSS light-dark() Stable in Practice is becoming increasingly widespread in frontend development. This article dives deep into its core principles and best practices from real project experience.
Basic Usage
Here is a complete example:
:root {
--bg: light-dark(#fff, #1a1a2e);
--text: light-dark(#333, #e0e0e0);
--accent: light-dark(#2563eb, #60a5fa);
color-scheme: light dark;
}
.carousel {
display: flex;
gap: 1rem;
overflow-x: auto;
scroll-snap-type: x mandatory;
scroll-padding: 1rem;
}
.carousel__item {
flex: 0 0 80%;
scroll-snap-align: start;
border-radius: 12px;
transition: scale 0.3s ease;
}
Pay attention to edge case handling — this is critical in production environments.
Advanced Usage
The key is understanding the core logic:
.container {
width: min(90%, 1200px);
margin-inline: auto;
padding-inline: clamp(1rem, 3vw, 3rem);
}
.grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(min(300px, 100%), 1fr));
gap: clamp(1rem, 2vw, 2rem);
}
.card {
container-type: inline-size;
}
@container (min-width: 400px) {
.card__content {
display: grid;
grid-template-columns: 200px 1fr;
}
}
Performance optimization needs to be tailored to specific scenarios; not every situation requires over-optimization.
Practical Cases
We can improve it in the following ways:
:root {
--bg: light-dark(#fff, #1a1a2e);
--text: light-dark(#333, #e0e0e0);
--accent: light-dark(#2563eb, #60a5fa);
color-scheme: light dark;
}
.carousel {
display: flex;
gap: 1rem;
overflow-x: auto;
scroll-snap-type: x mandatory;
scroll-padding: 1rem;
}
.carousel__item {
flex: 0 0 80%;
scroll-snap-align: start;
border-radius: 12px;
transition: scale 0.3s ease;
}
This solution has been running stably in production for over six months and has been validated in practice.
Performance Optimization
Let's start with the basic implementation:
.container {
width: min(90%, 1200px);
margin-inline: auto;
padding-inline: clamp(1rem, 3vw, 3rem);
}
.grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(min(300px, 100%), 1fr));
gap: clamp(1rem, 2vw, 2rem);
}
.card {
container-type: inline-size;
}
@container (min-width: 400px) {
.card__content {
display: grid;
grid-template-columns: 200px 1fr;
}
}
This code demonstrates the basic usage. In real projects, you also need to consider error handling and edge cases.
Common Pitfalls
Building on this foundation, we can further optimize: