Sub topic 6
Logical margin and padding
This chapter assumes you know the box model and the lang and dir attributes. It also assumes you have read the chapters on writing modes and on the block and inline axes.
From left and right to start and end
margin-left always means the left side of the screen. In a right-to-left page that is usually the wrong side. Logical margin and padding properties name a side by its position in the text flow. The browser resolves each name to a physical side using the element's writing-mode and direction.
| Logical property | Horizontal, `ltr` | Horizontal, `rtl` | `vertical-rl`, `ltr` |
|---|---|---|---|
| `margin-inline-start` | left | right | top |
| `margin-inline-end` | right | left | bottom |
| `margin-block-start` | top | top | right |
| `margin-block-end` | bottom | bottom | left |
Padding follows the same pattern: padding-inline-start, padding-inline-end, padding-block-start and padding-block-end.
The shorthands
margin-inline and margin-block set both sides of one axis. One value applies to both sides. Two values mean start, then end. padding-inline and padding-block work the same way.
.card {
inline-size: min(100%, 40ch);
margin-inline: auto;
padding-block: 1rem;
padding-inline: 1.5rem 1rem;
border-inline-start: 4px solid steelblue;
}Here padding-inline: 1.5rem 1rem puts 1.5rem on the start side and 1rem on the end side. In a left-to-right page the start side is the left. In a right-to-left page it is the right. margin-inline: auto centers the card along the inline axis.
One rule, both directions
<p dir="rtl" lang="ar" class="note">...</p>
<p dir="ltr" lang="en" class="note">...</p>
<style>
.note {
padding-inline-start: 2rem;
border-inline-start: 3px solid tomato;
}
</style>The Arabic paragraph gets its padding and border on the right. The English paragraph gets them on the left. You write no [dir="rtl"] override.
Common errors
- Assuming block means vertical.
margin-block-startis the top only in horizontal writing modes. Invertical-rlit is the right side. - Mixing physical and logical in one rule.
margin-leftandmargin-inline-startcan target the same physical side. The later declaration wins, in the usual cascade order. Pick one style per rule. - Expecting
margin-inline: autoto center vertically. It acts on the inline axis only. Vertical centering in horizontal text needs a different tool, such as flexbox or grid alignment. - Misreading percentages. Percentage margins and padding resolve against the containing block's inline size, even for the block-axis properties. This matches the physical properties.
Exercise
A button has margin-left: 0.5rem; padding: 0.25rem 1rem 0.25rem 2rem; where the 2rem on the left makes room for an icon. Rewrite it with logical properties so it works in right-to-left pages.
Show answer
Use margin-inline-start: 0.5rem; padding-block: 0.25rem; padding-inline: 2rem 1rem;. The first value of padding-inline is the start side, which holds the icon, and the second is the end side.