Home > Net >  How can you make a parent div wrap before its children wrap when using CSS flexbox?
How can you make a parent div wrap before its children wrap when using CSS flexbox?

Time:09-30

I have a parent div that has two main children. Each one has several elements inside. I need them to be responsive and wrap when there is not enough space.

CSS looks something like this:

.parent {
   display: flex,
   justify-content: center,
   flex-direction: row,
   flex-wrap: wrap
}

.children {
   display: flex,
   justify-content: center,
   flex-direction: row,
   flex-wrap: wrap
}

I would like the parent div to wrap, and then when there is still not enough space the children to wrap. The current behaviour is the opposite, the children wrap and then the parent will wrap when there is not enough space.

See the linked picture for a visual representation.

Can this be achieved? Can you somehow choose which level wraps first?

Visual representation

CodePudding user response:

Use display grid for parent element

dont use flex wrap

check the example below

.container {
  margin-left: auto;
  margin-right: auto;
  padding: 0 15px;
  height: 100vh;
  background-color: #f2f2f2;
}

.parent {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 10px;
}

.left,
.right {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 10px;
  background-color: yellow;
  padding: 15px;
}

.box {
  width: 40px;
  height: 40px;
  background-color: red;
  padding: 15px;
}

@media(max-width: 400px) {
  .left,
  .right {
    flex-direction: column;
  }
}
<div >
  <div >
    <div >
      <div ></div>
      <div ></div>
      <div ></div>
    </div>
    <div >
      <div ></div>
      <div ></div>
      <div ></div>
    </div>
  </div>
</div>

CodePudding user response:

I have a working example below:

I set the min width to 100px as an example.

.parent,
.child {
  display: flex;
  justify-content: center;
  flex-wrap: wrap;
}

.parent {
  gap: 2rem;
}

.child {
  flex-grow: 1;
  gap: 1rem;
}

.box {
  flex-grow: 1;
  flex-shrink: 1;

  min-width: 100px;
  aspect-ratio: 1 / 1;
}

CodePudding user response:

you can do this using JavaScript. Use window.innerWidth and window.innerHeight to get the dimension of the display and then add or remove class

//js 
var width=window.innerwidth;
if(width<1080)//According to your requirement
document.querySelector(".child").classList.add("rspclass");

add inline to your display inside child class

.rspclass{ 
display: flex,
   justify-content: center,
   flex-direction: row,
   flex-wrap: wrap
}

.child{
display:inline;
}
  • Related