Modern CSS Functions, Nesting and Logical Properties
Learning Objectives
- Use CSS math functions and custom property fallbacks.
- Write native CSS nesting.
- Use logical properties for writing-mode-aware layouts.
- Understand writing modes and progressive enhancement.
1. CSS Math Functions
.layout {
width: min(100% - 2rem, 72rem);
padding: clamp(1rem, 3vw, 2rem);
margin-inline: auto;
}
.card {
width: calc(50% - 1rem);
}CSS math functions include calc(), min(), max(), clamp() and additional typed math functions. Use them to express constraints and responsive sizing.
2. CSS Custom Properties
:root {
--brand-color: #2563eb;
--space: 1rem;
}
.button {
background-color: var(--brand-color);
padding: var(--space);
}
Custom properties store reusable values in the cascade. The var() function can supply a fallback: var(--brand-color, blue). Custom properties inherit by default and can be scoped to components.
3. Native CSS Nesting
.card {
padding: 1rem;
border-radius: 12px;
&:hover {
box-shadow: 0 4px 12px rgb(0 0 0 / 15%);
}
& .title {
font-weight: 700;
}
}Native CSS nesting lets related rules live inside a parent rule. The ampersand represents the parent selector in nested selector patterns. Use supported syntax and check target browser compatibility.
4. Logical Properties
.card {
padding-block: 1rem;
padding-inline: 1.5rem;
margin-inline: auto;
border-inline-start: 4px solid navy;
}Logical properties describe directions relative to the writing mode. Block refers to the block axis, and inline refers to the inline axis. They help support right-to-left and vertical writing systems.
5. Physical and Logical Properties
- margin-left refers to the physical left side.
- margin-inline-start refers to the start of the inline direction.
- padding-block controls the block-start and block-end sides.
- inset-inline controls inline-start and inline-end offsets.
6. Writing Modes and Direction
.vertical {
writing-mode: vertical-rl;
}
.rtl {
direction: rtl;
}Writing mode determines the orientation of lines and the block and inline axes. Direction sets text direction and affects the inline direction. Use semantic language and direction metadata in HTML where appropriate.
7. Modern Selector and Support Review
@supports (text-wrap: balance) {
h1 {
text-wrap: balance;
}
}Feature queries let you progressively enhance supported browsers. Text-wrap: balance can improve heading line balance where supported, but it should not replace careful content and layout design.