image
Photo by Rikonavt on Unsplash

Go Logical With CSS

Imagine you're building a house. What would that look like? Let's say you follow an architectural plan. Where would you begin?

Would you start at the foundations, building up the walls to match the plan? You could construct the roof in one piece and place it on top of the walls when complete. Good; now the interior isn't exposed to the elements from above anymore.

Where you place the windows affects how light enters the house. So, you fit the windows in the north and south-facing projections of the house.

Your house is now taken to a different world. On this world, the sun rises in the north and it rains parallel to the ground from the east. The house you built is no longer fit for purpose!

Imagine a house that reacted to its surroundings. So the roof would slide to the west wall and the windows would move the east walls. We could say that the house is doing what makes logical sense for it to do without any effort from you.

This idea is close to what CSS logical properties are for. Your layout understands its context and reflows the content accordingly.

The suns path across the sky and the incline of the weather trigger changes in the house.


With [CSS logical properties][1] your main triggers are the `writing-mode` and `dir` (directionality) .

The [writing-mode][2] CSS property sets whether lines of text are laid out horizontally or vertically, as well as the direction in which blocks progress. When set for an entire document, it should be set on the root element (HTML element for HTML documents).

In other words with writing-mode you control which direction text flows and how blocks of content stack. So writing-mode: horizontal-tb; flows text horizontally and stacks blocks of text from top-to-bottom.

The dir global attribute is an enumerated attribute that indicates the directionality of the element's text.

Directionality really only applies to horizontal text to support differences in languages such as Arabic verses English. Vertical text only ever reads from top to bottom. Know of otherwise then please send me a message :)

Below I've styled the highlighted region with `border-inline-start`. This adds a border to where the text starts. Click the checkboxes to change the directionality between `rtl` (right-to-left) and `ltr` (left-to-right) and see the border follow the start of the text.

See the Pen Writing Mode by Imran Nazir (@timeband-it)on CodePen.


`border-inline-start` is one example see the documentation to understand how `writing-mode` affects it. I hope that you can see from this simple example how logical properties make it easier to layout content in different languages.