This text was up to date on 28 July 2022 to incorporate the part protecting older browsers.
One thing I like about logical properties is the flexibility to set margins or padding on only a single axis on a component, whereas leaving the opposite alone. Say we’ve got a component on which we’ve set some padding utilizing the
/* This offers us 1rem padding all the best way round */
If, afterward, we wish to alter the padding solely on the x-axis (whereas preserving our unique worth on the y-axis), we’ve got a few selections:
- We might use
padding-right. Advantageous, however longer than our unique shorthand.
- We might use the shorthand, however remembering to incorporate our unique values.
padding: 1rem 2rem;
I’m not an enormous fan of getting to repeat the unique worth for the y-axis padding. We might summary these values out into customized properties — one thing like this:
padding: var(--py, 1rem) var(--px, 1rem);
Then again, there’s a logical property that allows us to regulate the padding on a single axis:
padding-inline refers back to the padding on the x-axis when the doc is within the left-to-right (default) or right-to-left writing mode.
padding-block refers back to the y-axis. (These instructions are reversed for a vertical writing mode.)
So as an alternative we might write:
The identical applies to margins, borders and a bunch of others. And take a look at the
inset property for an amazing positioning shorthand!
Logical properties are very properly supported in browsers now, so it’s an excellent time to start out utilizing them.
Whereas logical property help is excellent in fashionable browsers, as Šime identified, it’s a good suggestion to polyfill or present fallbacks for older browsers, in any other case customers of older browsers will expertise structure bugs. In case you use PostCSS then the PostCSS logical properties plugin ought to have you ever lined, in any other case it’s best to take into account testing for help utilizing a characteristic question.