How do I make the center element move to the line above when lacking space?

Viewed 90

I have three elements (divs for simplicity's sake). How do I make it so that, when the space is narrowed, the center element pops up to the line above the other two? I'm using media queries right now, but the center content can change width, so it breaks.

For example with:

<div class="container">
    <div class="Q">QWERTYUIOP</div>
    <div class="A">ASDFGHJKL0</div>
    <div class="Z">ZXCVBNM123</div>
</div>

When there is extra space it looks like this

QWERTYUIOP    ASDFGHJKL0    ZXCVBNM123

and when there is limited space it looks like this

       ASDFGHJKL0
QWERTYUIOP    ZXCVBNM123
2 Answers

You can achieve this behavior using media queries. So if you want to force the last 2 elements to next line when screen size is less than 560px, your css and html should be like this:

.container {
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
}
.nl {
    display: none;
    width:100%;
}
@media only screen and (max-width:560px){
   .A {
       order: 1;
       flex: 0 0 100%;
       text-align: center;
    }
    .Q {
       order: 2;
    }
    .Z {
       order: 3;
    }
}
<div class="container">
    <div class="Q">QWERTYUIOP</div>
    <div class="A">ASDFGHJKL0</div>
    <div class="Z">ZXCVBNM123</div>
</div>

I don't know if the author is allowed to use javascript?! ...but I don't know any other solution.

The css was not shown, so I made my own rules for the main .container. Flex rules are used. Also, I don't know if the class has a .container specific width ?!

In my example, I used the window resize event to visualize how my code works:

window.onresize = function() { ... }

but in production it needs to be replaced with a window load event:

window.onload = function() { ... }

If this example does not suit the author, then I think that this example will be useful to others :)

window.onresize = function() {

let container = document.querySelector('.container');
let Q_div = document.querySelector('.Q');
let A_div = document.querySelector('.A');
let Z_div = document.querySelector('.Z');

let sum_div = Q_div.offsetWidth + A_div.offsetWidth + Z_div.offsetWidth;

  if (container.offsetWidth <= sum_div) { 
    A_div.classList.add('class_for_A');
  } else {
    A_div.classList.remove('class_for_A');
  }
}
.container {
  display: flex;
  flex-wrap: wrap-reverse;
  justify-content: space-between;
  width: 500px;
  max-width: 100%;
}

.A.class_for_A {
  order: 1;
  margin: auto;
}
<div class="container">
    <div class="Q">QWERTYUIOP</div>
    <div class="A">ASDFGHJKL0</div>
    <div class="Z">ZXCVBNM123</div>
</div>

Related