๐ŸŽ Checkout my Learn React by Making a Game course and get 1 month Free on Skillshare!

CSS Logical Properties

Create spacing that works regardless of the direction of your content or the environment of your users.

Say you want to put some space between two inline items: what do you do? Probably something like this:

.my-element {
    margin-left: 1em;
}

This approach is fine and has been for a long time with CSS, but what happens when the content direction changes? That left margin suddenly becomes problematic because it no longer matches and makes the content look awkward.

Western languages read left to right, but other languages such as Arabic, read right to left. Some languages even read top to bottom, like traditional Chinese.

Our CSS should be as flexible as possible, so instead of explicitly setting a left, right, top or bottom value to margins, we should instead be using a logical property.

Hereโ€™s that same example from the start, but with a logical property:

.my-element {
    margin-inline-start: 1em;
}

What this now does is instead of saying โ€œadd margin to the leftโ€, it says โ€œregardless of direction, put margin on the starting sideโ€. If the language of the document was right to left, like Arabic, that margin would be on the right hand side.

Why is this important?

The web is global and open, so making presumptions about the users of your website is pretty dangerous.

A variety of factors come into play when someone visits your site, such as connection speed, device power and spoken language. They could also be using a translation extension. Itโ€™s our job as web developers to make our content as flexible as possible to meet user needs, regardless of what those needs are, using the powerful, flexible tools that are given to us by the web platform.

Logical properties are a perfect example of this and they have a huge browser support, so you should absolutely use them today.

Resources and further learning permalink

This is only a quick intro to logical properties, but luckily, some other fine folks from around the web have written about them in detail:

CSS Logical Properties - CSS-Tricks
CSS Logical Properties and Values - MDN
Understanding Logical Properties And Values
CSS Logical Properties - Adrian Roselli

๐Ÿ“– 50 Javascript, React and NextJs Projects

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.

๐Ÿ“– 50 Javascript, React and NextJs Projects

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.


Leave a Reply

Your email address will not be published. Required fields are marked *