Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make a flexbox child div 50% width and grow to 100% on wrap

Tags:

html

css

I have the following

<div style="max-width:100%;flex-wrap:wrap;display:flex">
   <div style="width:50%;flex-grow:1"></div>
   <div style="width:50%;flex-grow:1"></div>
</div>

What I'm trying to do is to have the two child elements start off at 50% width. When the window size is reduced, I want the second one to wrap below the first one and both of them to grow to 100%. Right now the first one is starting of at 100%. I'm using Chrome.

like image 283
user994165 Avatar asked Nov 27 '18 20:11

user994165


2 Answers

Forcing the items to width:50% is redundant since you would be using flex, which can split the width equally if the flex-grow is equal for both items and flex-basis is set to 0. To get the effect of wrapping "at certain point" you can either use @jake's approach, or define a min-width for the elements, after which the wrap will occur naturally. Here is an example in action.

like image 101
Piotr Wicijowski Avatar answered Sep 28 '22 06:09

Piotr Wicijowski


Adding @media would work or you can also check out this article on responsive design for flex

.parent{
  background: tomato;
  height: 100%;
  padding: 10px;
  display: flex;
  flex-wrap:wrap;  
}
.parent > div {
  width: 50%;
  height: 100px;
  }
@media only screen and (max-width: 600px){
  .parent > div{   
    width: 100%;
  }
}
<div class="parent">
  <div style="background: yellow"></div>
  <div style="background: green"></div>
</div>
like image 44
Victoria Le Avatar answered Sep 28 '22 08:09

Victoria Le