I have 5 flex items within a flex container:
<section class="dishesNewest">
<div class="newDish">
<a href="#"><img src=${e.image} alt="" class="newDishImg lazyLoad" /></a>
<h1 class="newDishTitle">${e.title}</h1>
</div>
<div class="newDish">
<a href="#"><img src=${e.image} alt="" class="newDishImg lazyLoad" /></a>
<h1 class="newDishTitle">${e.title}</h1>
</div>
<div class="newDish">
<a href="#"><img src=${e.image} alt="" class="newDishImg lazyLoad" /></a>
<h1 class="newDishTitle">${e.title}</h1>
</div>
<div class="newDish">
<a href="#"><img src=${e.image} alt="" class="newDishImg lazyLoad" /></a>
<h1 class="newDishTitle">${e.title}</h1>
</div>
<div class="newDish">
<a href="#"><img src=${e.image} alt="" class="newDishImg lazyLoad" /></a>
<h1 class="newDishTitle">${e.title}</h1>
</div>
</section>
styles.css
.dishesNewest {
margin: 10rem auto 25rem auto;
display: flex;
padding: 0 5%;
justify-content: center;
}
.newDish {
display: flex;
flex-direction: column;
min-width: 150px;
gap: 2rem 0;
padding: 8px;
}
on a screen width of 800px i want to change the width of each item to something like 40% or 50% so it display as 2 divs
per row :
@media only screen and (max-width: 800px) {
.newDish {
width: 45%
}
}
but the flex item totally ignores both width
and flex-basis
, and it doesnt matter if using pixels, percentage or anything else it doesnt work, why is that happening?
2
Answers
The
width
declaration has no effect due to the fact thatmin-width
takes precedence over thewidth
declaration, and so the elements will be150px
width instead. You could override this by settingmin-width: 0
in your media query:Then, to display the elements as two per row, consider allowing the flex children to wrap by setting
flex-wrap: wrap
on the flex parent container:You can use
flex-wrap
in.dishesNewest
along with that rule for 800px. If flex-wrap is not set in the flex container it will never wrap.When 2 containers cannot fit in the same row because of the min-with (150px) they will break in just one column
(I’ve added colors for visibility purposes)