Search code examples
htmlcssalignmentright-to-left

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


How to align a HTML element to start or end position instead left or right like Android XML. I want to position an element on right side when LTR (left to right) direction and set position on left side when RTL direction.

I tried

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

Is there any way to do the same?


Solution

  • .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>

    Use flex-direction with value row for left-to-right, and row-reverse for right-to-left.

    Use justify-content to align items in the main axis (flex-direction with value of row or row-reverse - main axis: x, column or column-reverse - main axis: y). Where flex-end or flex-start will mean the end or beginning of the axis's direction - using flex-end will align to the right if you use flex-direction: row (ltr), and it will align to the left if you use flex-direction: row-reverse (rtl).

    Update

    The above is all true, but if you specify dir on an element, the flex container will automatically detect the direction. (if you set dir="rtl", it will behave as flex-direction: row-reverse without actually setting it)

    Knowing this, you can check:

    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>