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

How to align a HTML element to start or end position instead left or right

如何将 HTML 元素对齐到开始或结束位置,而不是像 Android XML 那样向左或向右对齐。我想在 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>

使用 flex-direction,从左到右的值为 row,从右到左的值为 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>