skip to Main Content

I have a div which has a display of flex, now I have two containers inside this div.
I want to place the second container to the left of the first one, but the second one comes below in the HTML.

I also want to make it so that, if the size of the first container increases, (due to longer text), it should also push the second container to the left.
I’ve tried using float, but it is ignored due to using display flex. I tried using margin-left:auto but no result, same with margin-right auto.

https://jsfiddle.net/puz1qf7v/2/

.main {
  height: 200px;
  width: 500px;
  background-color: lightblue;
  display: flex;
}

.first {
  height: 40px;
  background-color: skyblue;
  margin: 10px;
}

.second {
  height: 40px;
  background-color: crimson;
  margin: 10px;
}
<div class="main">
  <div class="first">
    skyblue yabadabadoo
  </div>
  <div class="second">
    crimson yabadabadoo
  </div>
</div>

2

Answers


  1. Use order to change the order

    .main {
      height: 200px;
      width: 500px;
      background-color: lightblue;
      display: flex;
    }
    
    .first {
      height: 40px;
      background-color: skyblue;
      margin: 10px;
    }
    
    .second {
      height: 40px;
      background-color: crimson;
      margin: 10px;
      order:-1;
    }
    <div class="main">
      <div class="first">
        skyblue yabadabadoo
      </div>
      <div class="second">
        crimson yabadabadoo
      </div>
    </div>
    Login or Signup to reply.
  2. Seeing as you have a flex parent div, you could always use reverse to change the order of all your elements (and justify-content to float them to the left):

    .main {
        height: 200px;
        width: 500px;
        background-color: lightblue;
        display: flex;
        flex-direction: row-reverse;
        justify-content: flex-end;
    }
    
    .first {
        min-height: 40px;
        height: fit-content;
        background-color: skyblue;
        margin: 10px;
    }
    
    .second {
        min-height: 40px;
        height: fit-content;
        background-color: crimson;
        margin: 10px;
    }
    <div class="main">
        <div class="first">
          skyblue yabadabadoo yabadabadoo yabadabadoo yabadabadoo yabadabadoo yabadabadoo yabadabadoo yabadabadooyabadabadoo yabadabadoo yabadabadoo yabadabadoo yabadabadoo yabadabadoo yabadabadoo
        </div>
        <div class="second">
          crimson yabadabadoo yabadabadoo yabadabadoo
        </div>
    </div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search