简体   繁体   中英

Flexbox that goes full width when forced onto new line?

I have two divs lined next to each other using the following CSS:

.overlay {
  display: flex;
  flex-wrap: wrap;   
}

.mainContent {
  flex-grow: 1;
  flex-basis: auto;
  margin: 5px;
}

.interactions {
  flex-basis: auto;
  flex-grow: 1;
  max-width: 400px;
  margin: 5px; 
}

When the width of the screen gets too small (ie .interactions can no longer fit) a new row is created in which interactions are placed.

What I'd like to do when that happens is for interactions to switch to max-width: 100%, is there any way to do this without using javascript?

There's two situations here

screen gets too small

  1. if screen goes below 400px we're okay with the rules so far

  2. if screen is above 400px but still too small, we end up with conflicting max-widths

is there anyway to do this without using javascript?

It can be achieved with media queries

@media only screen and (max-width: 600px) {
  .instructions { min-width: 100% }
}

maybe you should use media queries?

@media (max-width: 400px) { 
  .interactions {
    max-width: 100%;
  }
}

you shuld to use the nowrap property, the flex-wrap: wrap create new line when the intenrnal divs are too little, the nowrap not create, the code to remain in the same line is

.overlay {
    display: flex;
    flex-wrap: nowrap;

  }
  .mainContent {
    flex-grow: 1;
    flex-basis: auto;
    margin: 5px;
  }

  .interactions {
    flex-basis: auto;
    flex-grow: 1;
    max-width: 400px;
    margin: 5px; 
  }

you can find the documentation here https://www.w3schools.com/cssref/css3_pr_flex-wrap.asp

Also you can find other details of the usage and the browser compatibility here https://caniuse.com/#search=flex-wrap

Using media queries is a challenge here because the breakpoint at which the problem occurs is dependent on the size of the flexible width .mainContent

So a better approach would be to have a min-width on .mainContent and use a media query for the breakpoint which is a sum of the min-width of .mainContent and max-width of .interactions + margins

.overlay {
    display: flex;
    flex-wrap: wrap;
    justify-content:stretch;
}
.mainContent {
    flex-grow: 1;
    flex-basis: auto;
    min-width:400px;
    margin: 5px;
}
.interactions {
    flex-basis: auto;
    flex-grow: 1;
    max-width:400px;
    margin: 5px; 
}
@media only screen and (max-width: 840px){
    .mainContent, .interactions{
        max-width:none;
        min-width:none;
    }
}

See it in action here: https://jsfiddle.net/gnu12Lfs/

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