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.

Digram showing how margin-left isn’t effective when the text direction is switched
When the direction of content is switched, the left margin is problematic, rather than helpful.

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.

Digram showing how margin-inline-start is much more effective
When we use logical properties, the margin becomes flexible based on the content direction.

Click the button in this demo to see how the margin is now reactive to the content direction:

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

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:


👋 Hello, I’m Andy and I’ll help you build fast & visually stunning websites.

I’m the founder of Set Studio, a creative agency that specialises in building stunning websites that work for everyone. If you’ve got a project in mind, get in touch.


Back to blog