Two divs side by side with flex

Viewed 4473

I have 4 cells in laptops mode And when I want to have two cells side by side in phone mode I have to remove the flex in the outer div But I can no longer have an auto height div . How to fix this

<div class="box">
    <div class="row">
        <div class="cell"></div>
        <div class="cell"></div>
        <div class="cell"></div>
        <div class="cell"></div>
    </div>
</div>

CSS

.box {
    height: auto;
    padding: 50px;
    background-color: red;
}
.row {
    display: flex;
}
.cell {
    float: right;
    width: 50%;
    height: 50px;
}
1 Answers

You must use 2 more css attribute, flex and flex-wrap.

To ensure the cell wrap to the next line when the screen is too small, you must add the property flex-wrap : wrap to the row class.

Then you need to define a flex property for the cell.

The flex property is defined like that

flex : flex-grow flex-shrink flex-basis;

Flex-grow and flex-shrink are grow and shrink coefficient. Here, all the cell must have the same width, so we do not care about this value (I've set these to 1). Flex-basis indicate the default width of your cell

Here's an example :

.box {
    height: auto;
    padding: 50px;
    background-color: red;
}
.row {
    display: flex;
    flex-wrap:wrap;
}
.cell {
    flex: 1 1 200px;
    height: 50px;
    border:1px solid black;
    background-color: blue;
}
<div class="box">
    <div class="row">
        <div class="cell"></div>
        <div class="cell"></div>
        <div class="cell"></div>
        <div class="cell"></div>
    </div>
</div>

Related