CSS logical properties: using the margin-block and margin-inline instead of the default margin

Take the following example. We have a link, followed by a few words. And we want a 20px margin space between the link and the text.

.container {
    border: 1px solid black;
    display: float;
    padding: 5px;
}

a {
    margin-right: 20px; 
    background-color: yellow;
}
A link

some text

In this content adding a margin-right: 20px; makes perfect sense.

But what if the flex-direction of the container changes in reverse? Or the user is using a translation extension? Arabic is read right to left.

Then our element will look like this:

A link

some text

The margin will still be on the right side, and we will have to add some more lines of code to make it work again.

Meet the CSS logical properties. We can replace the plain old margin with margin-inline-start: 20px;.

a {
    margin-inline-start: 20px; 
}

What it does is instead of saying "add a margin to the rightโ€, we will have โ€œregardless of direction, put a margin on the starting sideโ€. It does not matter if the starting side is on the left or the right.

A link

some text

Pretty cool, no? ๐Ÿ™‚

If we want to replace some other margins, we can use the following table of correspondence:

margin-top      -> margin-block-start
margin-left     -> margin-inline-start
margin-right        -> margin-inline-end
margin-bottom   -> margin-block-end

And it works also with border and padding.

๐Ÿ“– 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.


2 Replies

Leave a Reply

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

Home Screencasts Best of Newsletter Search X

๐Ÿ“– 50 Javascript, React and NextJs Projects

Hi friend! Before you go, just wanted to let you know about the 50 Javascript, React and NextJs Projects FREE ebook.

One of the best ways to learn is by doing the work. Choose from 8 project categories and get started right away:

  • Business & Real-World
  • Games & Puzzles
  • Fun & Interesting
  • Tools & Libraries
  • Personal & Portfolio
  • Project Add-Ons
  • Productivity
  • Clones

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects complete with project briefs and wireframes!

Keep building and level up! Get all projects as an ebook right to your inbox!

X