4

I have a flex box which has flex items in it, each having a certain order.

I want to set it so that when the flex box (not the screen, etc.) gets smaller than 500px the order changes (and maybe also one of the margins).

Here's the code:

HTML

<div class="flex-box">
  <div class="flex-item-0"></div>
  <div class="flex-item-0"></div>
  <div class="flex-item-0"></div>
  <div class="flex-item-2"></div>
  <div class="flex-item-2"></div>
  <div class="flex-item-3"></div>
</div>

CSS

.flex-box{
  display: flex;
  flex-flow: row wrap;
  align-items: center;
  justify-content: center;
}
.flex-item-0{
  order: 0;
}
.flex-item-2{
  order: 2;
}
.flex-item-3{
  order: 3;
  margin-left: auto;
}

and when the flex-box gets less than 500px (or whatever specified amount) I want flex-item-3 to change to:

.flex-item-3{
  order: 1;
  /*margin-left: auto;*/
}

(I comment out the margin-left: auto; so the it is noted that is has been taken out)

I know there are @media queries however I am not sure how they would apply in this situation.

Does anyone know how to change a CSS style whenever the containing box gets less than a specific width? (CSS solution preferred but fine with JS/jQuery)

The Codesee
  • 3,714
  • 5
  • 38
  • 78
4lackof
  • 1,250
  • 14
  • 33

1 Answers1

3

With CSS, as you said, you can use media queries.

In this case you would use:

@media (max-width:500px) {
  .flex-item-3 {
    order: 1;
    margin-left: initial;
  }
}

CODE SNIPPET:

.flex-box {
  display: flex;
  flex-flow: row wrap;
  align-items: center;
  justify-content: center;
  /*---Demo---*/
  margin-top: 40px;
  border: 1px solid #262626;
  /*---Demo---*/
}
.flex-item-0 {
  order: 0;
}
.flex-item-2 {
  order: 2;
}
.flex-item-3 {
  order: 3;
  margin-left: auto;
  /*---Demo---*/
  font-weight: bold;
  background-color: tomato;
  /*---Demo---*/
}
@media (max-width: 500px) {
  .flex-item-3 {
    order: 1;
    margin-left: initial;
  }
}
<div class="flex-box">
  <div class="flex-item-0">0</div>
  <div class="flex-item-0">0</div>
  <div class="flex-item-0">0</div>
  <div class="flex-item-2">2</div>
  <div class="flex-item-2">2</div>
  <div class="flex-item-3">3</div>
</div>
Ricky Ruiz
  • 25,455
  • 6
  • 44
  • 53