🎁 Checkout my Learn React by Making a Game course and get 1 month Free on Skillshare!

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 *