Thursday, April 18, 2024
HomeCSSLogical Properties for Helpful Shorthands

Logical Properties for Helpful Shorthands


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 padding shorthand:

/* This offers us 1rem padding all the best way round */
.field {
padding: 1rem;
}

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:

  1. We might use padding-left and padding-right. Advantageous, however longer than our unique shorthand.
.box--some-variant {
padding-right: 2rem;
padding-left: 2rem;
}
  1. We might use the shorthand, however remembering to incorporate our unique values.
.box--some-variant {
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:

.field {
padding: var(--py, 1rem) var(--px, 1rem);
}

.box--some-variant {
--px: 2rem;
}

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:

.field {
padding: 1rem;
}

.box--some-variant {
padding-inline: 2rem;
}

Codepen demo →

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.

Replace

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.



RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments