I am refactoring non-responsive code and am trying to display the below code as a 2x2 grid using Flexbox. I have tried using display:
HTML (no changes)
CSS
.gallery {}
.gallery ul {
display: flex;
flex-flow: row wrap;
list-style: none;
margin: 32px 0;
}
.gallery li {
margin: 0 10px;
flex-basis: calc(50% - 20px); /* width minus margins */
}
.gallery img {
width: 100%; /* occupy 100% width of li container */
height: auto;
}
DEMO
NOTES:
When you create a flex container (by applying display: flex
or display: inline-flex
to an element), the child elements become flex items. The descendants of the flex container beyond the children do not become flex items and, therefore, do not accept flex properties.
In your code, .gallery
is the flex container. This means that its children – h2
and ul
– are flex items. However, the children of the ul
are not flex items and flex properties don't apply. That's why the images, contained in the li
elements, "are acting as block elements and won't sit side by side".
To apply flex properties to the li
elements, their parent must be made a flex container. By adding display: flex
to the ul
, the li
's become flex items. (Note, the img
elements remain inline elements because they are not children of the flex container.)