Reputation: 933
I have a DIV that is declared with style="direction:ltr" in-order to display right to left items.
My issue that if I declare a div with a right margin (margin-right), this margin does not automatically switch to the left side when the div is RTL.
This forces me to style every div that I want to be RTL with margin-left.
Can I use some CSS paramter that would always put the margin at the end of the DIV and will automatically switch when using RTL? (Horizontally)
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<style>
.container{
display:flex;
flex-direction:row;
}
.text{
margin-right:30px;
}
</style>
<div class="container">
<div class="text">On this DIV the margin between the text and the icon is correct.</div>
<div class="icon"><i class="fa fa-inbox" style="margin-right:3px; font-size:24px"></i><div>
</div>
<div class="container" style="direction:rtl">
<div class="text">On this RTL DIV the margin between the text and the icon is missing because the margin parameter is <b>margin-right</div>
<div class="icon"><i class="fa fa-inbox" style="margin-right:3px; font-size:24px"></i><div>
</div>
Upvotes: 5
Views: 6203
Reputation: 4681
Pure CSS approach
instead of using left
or right
use *-inline-start
and *-inline-end
.ltr { /*default not required*/ }
.rtl { direction: rtl; }
.mainDiv { border: 1px solid #DD9900; padding: 10px; }
.childDiv {
margin-inline-end: 50px;
border: 2px solid #99DD00;
}
<div class="mainDiv">
<div class="childDiv ltr"> Hello World </div>
<div class="childDiv rtl"> مرحبا بالعالم </div>
</div>
https://developer.mozilla.org/en-US/docs/Web/CSS/margin-inline-start
Upvotes: 1
Reputation: 191
Use css property "...-inline-start" instead, that will align it to either the left or the right depending on the browser direction. You can test that easily by adding dir="rtl" to the html element.
.text {
margin-inline-start: 10px;
}
PS.: inline is for left/right, use block for top/bottom, e.g. margin-block-start to add margin to the top, padding-inline-start to add padding to the left in ltr languages and rigth in rtl languages
Upvotes: 19
Reputation: 584
You can differentiate the elements in even or odd, to give them a margin to each as appropriate. Or the container to give another class makes them different, such as container left-to-right
and container right-to-left
.
.container:nth-child(odd) .text {
margin-right: 30px;
}
.container:nth-child(even) .text {
margin-left: 30px;
}
Or this:
.container.left-to-right .text {
margin-right: 30px;
}
.container.right-to-left .text {
margin-left: 30px;
}
Upvotes: 1