Why CSS Logical Box Outshine the Box Model

Explore the advantages of CSS Logical Boxes over the Box Model

Imagine that you have some right-to-left (RTL) content on your website your left might be probably the physical right, so if you are usually setting margin-left: 100px for some elements, you might want to replace that with margin-right: 100px

Given this example, we have a basic left-to-right language page

<html dir="ltr" lang="en">
  <header> ... </header>
  <body>
    <header class="masthead">
        <h1 class="pagetitle">CSS Logical Properties</h1>
    </header>
    <main class="demo-area">
        <p>The blockquote below is supposed to have an indent and a vertical line at the start.</p>
        <blockquote>Traditional box directions make little sense when you start working with multiple text directions, writing modes, and flexible boxes and grids where the flow direction can be changed.</blockquote>
    </main>
</body>
</html>

The result:

Remember, we want to support right-to-left languages as well. We need to change from "rtl" to "ltr".Automatically, the words will be switched from right to left

<html dir="rtl" lang="en">
   ...
</html>

The result is not what we expected.

The border hasn't changed at all; it is because we have a static border-left CSS property here and that's become an issue for us

blockquote {
    border-left: 1rem solid black;
    padding-left: 1rem;
}

In modern web development, the traditional box model is becoming less convenient, thanks to the adoption of CSS logical properties that offer greater flexibility and adaptability in layout and positioning

Introduction to CSS logical box

CSS logical properties, including inline-start, inline-end, block-start, andblock-end, provide a way to describe layout and positioning in a language-agnostic manner. Instead of using fixed directions like "top," "left," "bottom," and "right," which can be problematic in multilingual and right-to-left (RTL) layouts, logical properties adapt to the writing mode of the content.

Let's use our new knowledge to solve the problem

blockquote {
    border-inline-start:1rem solid black;
    padding-inline-start:1rem;
    /** inline-start = left
        inline-end = right
        block-start = top
        block-end = bottom **/
}

As you can tell, no matter what language we choose, the border will align with the natural flow of the language

Even browsers use logical box model for their default style

Conclusion

Using logical properties allows web developers to create more adaptable and accessible layouts that automatically adjust based on the content's language and direction, providing better support for internationalization and right-to-left languages without the need for complex CSS changes.