Logical Properties for Useful Shorthands
This article was updated on 28 July 2022 to include the section covering older browsers.
Something I like about logical properties is the ability to set margins or padding on just a single axis on an element, while leaving the other alone. Say we have an element on which we’ve set some padding using the
/* This gives us 1rem padding all the way around */
If, later on, we want to adjust the padding only on the x-axis (while preserving our original value on the y-axis), we have a couple of choices:
- We could use
padding-right. Fine, but longer than our original shorthand.
- We could use the shorthand, but remembering to include our original values.
padding: 1rem 2rem;
I’m not a huge fan of having to repeat the original value for the y-axis padding. We could abstract those values out into custom properties — something like this:
padding: var(--py, 1rem) var(--px, 1rem);
On the other hand, there is a logical property that enables us to adjust the padding on a single axis:
padding-inline refers to the padding on the x-axis when the document is in the left-to-right (default) or right-to-left writing mode.
padding-block refers to the y-axis. (Those directions are reversed for a vertical writing mode.)
So instead we could write:
The same applies to margins, borders and a bunch of others. And check out the
inset property for a great positioning shorthand!
Logical properties are very well supported in browsers now, so it’s a good time to start using them.
While logical property support is very good in modern browsers, as Šime pointed out, it’s a good idea to polyfill or provide fallbacks for older browsers, otherwise users of older browsers will experience layout bugs. If you use PostCSS then the PostCSS logical properties plugin should have you covered, otherwise you should consider testing for support using a feature query.