简体   繁体   中英

Change order of flex items when flex box width changes

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)

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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM