CSS Logical Properties
CSS Logical Properties and Values provide a way to control layout through logical, rather than physical, direction and dimension mappings. They allow you to build layouts that work automatically across different writing modes (e.g., Left-to-Right, Right-to-Left, Top-to-Bottom).
1. The Concept
Physical properties like margin-left, padding-top, or width are tied to the physical screen.
Logical properties like margin-inline-start, padding-block-start, or inline-size are tied to the flow of content.
- Block Axis: The direction in which blocks are stacked (usually top-to-bottom).
- Inline Axis: The direction in which text flows (usually left-to-right).
2. Sizing
Instead of width and height, use:
inline-size: Corresponds towidthin horizontal writing modes.block-size: Corresponds toheightin horizontal writing modes.
.box {
inline-size: 300px; /* Width in LTR/RTL */
block-size: 200px; /* Height in LTR/RTL */
}
3. Margins, Padding, and Borders
Replace top, bottom, left, right with block-start, block-end, inline-start, inline-end.
| Physical | Logical |
|---|---|
margin-top |
margin-block-start |
margin-bottom |
margin-block-end |
margin-left |
margin-inline-start (LTR) / margin-inline-end (RTL) |
margin-right |
margin-inline-end (LTR) / margin-inline-start (RTL) |
Shorthands
margin-block: Sets both start and end block margins. In a standard horizontal writing mode (like English), this is equivalent tomargin-topandmargin-bottom.margin-inline: Sets both start and end inline margins. In a standard horizontal writing mode (like English), this is equivalent tomargin-leftandmargin-right.
The key difference is that margin-block follows the flow of blocks (paragraphs, divs), while margin-inline follows the flow of text.
.card {
padding-inline: 20px; /* Left and Right padding */
margin-block: 10px; /* Top and Bottom margin */
border-block-end: 1px solid black; /* Bottom border */
}
4. Positioning
For position: absolute or fixed, use logical offsets.
top->inset-block-startbottom->inset-block-endleft->inset-inline-startright->inset-inline-end
.badge {
position: absolute;
inset-block-start: 0;
inset-inline-end: 0; /* Top-Right in LTR, Top-Left in RTL */
}
5. Why use them?
If you translate your site into a Right-to-Left (RTL) language like Arabic or Hebrew, logical properties ensure your layout flips correctly without writing a separate RTL stylesheet.