Say you want to put some space between two inline items: what do you do? Probably something like this:
- Code language
- css
.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:
- Code language
- css
.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.
Click the button in this demo to see how the margin is now reactive to the content direction:
See the Pen Piccalilli Demo - Logical Properties by piccalilli (@piccalilli) on CodePen.
Why is this important?permalink
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 learningpermalink
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