如何将 HTML 元素与开始或结束位置对齐,而不是向左或向右对齐



如何像Android XML一样将HTML元素与开始或结束位置对齐,而不是向左或向右对齐。我想在 LTR(从左到右(方向时将元素放置在右侧,并在 RTL 方向时将元素设置在左侧。

我试过了

.element{float:end;}
.element{position: absolute; end: 10px;}

有什么办法可以做同样的事情吗?

.flex-container {
display: flex;
width: 300px;
height: 100px;
background-color: gray;
justify-content: flex-end;
margin: 20px;
flex-direction: row /*default*/
}
span {
width: 100px;
height: 100px;
background-color: red;
}
<div class="flex-container" dir="ltr">
<span></span>
</div>
<div class="flex-container" dir="rtl">
<span></span>
</div>

使用值rowflex-direction表示从左到右,row-reverse表示从右到左。

使用justify-content对齐主轴中的项目(flex-direction值为rowrow-reverse- 主轴:x、columncolumn-reverse- 主轴:y(。 其中flex-endflex-start表示轴方向的结束或开始 - 如果使用flex-direction: row(ltr(,则使用flex-end将向右对齐, 如果您使用flex-direction: row-reverse(RTL(,它将向左对齐。

更新

以上都是正确的,但是如果您在元素上指定dir,flex 容器将自动检测方向。(如果您设置dir="rtl",它将在不实际设置的情况下表现为flex-direction: row-reverse(

知道了这一点,您可以检查:

window.onload = () => {
if (navigator.language/*=== rtlLanguage*/) {
document.body.dir = "rtl";
}
};
.flex-container {
display: flex;
width: 300px;
height: 100px;
background-color: gray;
justify-content: flex-end;
margin: 20px;
flex-direction: row /*default*/
}
span {
width: 100px;
height: 100px;
background-color: red;
}
<body>
<div class="flex-container">
<span></span>
</div>
</body>

最新更新