Modern CSS Techniques Every Developer Should Know
Modern CSS Techniques Every Developer Should Know
CSS has evolved significantly over the years. This guide covers the latest techniques that can help you build better user interfaces.
CSS Grid Layout
CSS Grid is a powerful layout system for creating complex designs:
.grid-container {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
grid-gap: 2rem;
align-items: start;
}
.grid-item {
background: var(--card-background);
border-radius: 8px;
padding: 1.5rem;
}CSS Custom Properties (Variables)
Use CSS variables for theming and dynamic styling:
:root {
--primary-color: #3b82f6;
--secondary-color: #10b981;
--font-size-base: 1rem;
--spacing-unit: 1rem;
}
.themed-component {
color: var(--primary-color);
font-size: var(--font-size-base);
margin: var(--spacing-unit);
}
/* Dark theme */
[data-theme="dark"] {
--primary-color: #60a5fa;
--secondary-color: #34d399;
}Container Queries
Container queries allow responsive design based on container size:
.card-container {
container-type: inline-size;
}
@container (min-width: 400px) {
.card {
display: flex;
gap: 1rem;
}
.card-image {
flex: 0 0 150px;
}
}CSS Subgrid
Subgrid allows grid items to participate in the parent grid:
.parent-grid {
display: grid;
grid-template-columns: 1fr 2fr 1fr;
}
.child-grid {
display: grid;
grid-column: 1 / -1;
grid-template-columns: subgrid;
}Advanced Selectors
Use modern CSS selectors for more precise targeting:
/* :has() selector */
.card:has(.featured-badge) {
border: 2px solid var(--primary-color);
}
/* :is() selector */
:is(h1, h2, h3) {
font-family: 'Inter', sans-serif;
font-weight: 600;
}
/* :where() selector */
:where(.btn, .button) {
padding: 0.5rem 1rem;
border-radius: 0.25rem;
}CSS Cascade Layers
Organize your CSS with cascade layers:
@layer reset, base, components, utilities;
@layer reset {
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
}
@layer base {
body {
font-family: system-ui, sans-serif;
line-height: 1.5;
}
}
@layer components {
.card {
background: white;
border-radius: 8px;
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}
}CSS Nesting
Native CSS nesting reduces repetition:
.navbar {
background: var(--nav-background);
ul {
display: flex;
list-style: none;
li {
margin-right: 1rem;
a {
text-decoration: none;
color: var(--nav-link-color);
&:hover {
color: var(--nav-link-hover-color);
}
&.active {
font-weight: bold;
}
}
}
}
}CSS Anchor Positioning
Position elements relative to anchor points:
.tooltip {
position: absolute;
anchor-name: --tooltip;
}
.tooltip-trigger {
position-anchor: --tooltip;
&:hover + .tooltip {
position-area: bottom;
translate: -50% 0;
}
}Conclusion
These modern CSS techniques can significantly improve your styling workflow and enable you to create more sophisticated user interfaces. As browser support continues to improve, these features are becoming essential tools for frontend developers.