带有 RTL 元素的 CSS 边距

Dav*_*ekh 5 html css

我有一个用style="direction:ltr " 声明的 DIV,以便从右到左显示项目。

我的问题是,如果我声明一个带有右边距 ( margin-right ) 的 div,当 div 为 RTL 时,该边距不会自动切换到左侧。

这迫使我用margin-left来设计每个我想要 RTL 的 div 。

我可以使用一些 CSS 参数来始终将边距放在 DIV 的末尾,并在使用 RTL 时自动切换吗?(水平)

<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>
Run Code Online (Sandbox Code Playgroud)

小智 16

请改用 css 属性“...-inline-start”,这将根据浏览器方向将其向左或向右对齐。您可以通过将 dir="rtl" 添加到 html 元素来轻松测试。

.text {
    margin-inline-start: 10px;
}
Run Code Online (Sandbox Code Playgroud)

PS.:inline用于左/右,使用block用于顶部/底部,例如margin-block-start在顶部添加边距,padding-inline-start在ltr语言中向左侧添加填充,在rtl语言中使用rigth


小智 1

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;
}
Run Code Online (Sandbox Code Playgroud)

Or this:

.container.left-to-right .text {
  margin-right: 30px;
}

.container.right-to-left .text {
  margin-left: 30px;
}
Run Code Online (Sandbox Code Playgroud)

Example