I am doing an exercise with responsive layouts and floats. In my layout I have four sections that are displayed side by side using floats. One small section, then a big one, and then two more small sections. For smaller screen sizes, I want the "big" section to move up and be displayed first, taking the full width.
The three small sections should go below the big section, side by side. I can't figure out how to change the order of the sections, so the first small section can be in a row with the other two. How can I move the big section up (or move down the first small section) with just CSS?
section {
height: 350px;
width: 19.4444%;
float: left;
border: 1px solid black;
}
.big {
width: 41.6666%;
}
<section ></section>
<section ></section>
<section ></section>
<section ></section>
CodePudding user response:
First, wrap the Sections and apply Flexbox to the wrapping element. Then also apply flex-wrap: wrap
to the same element.
Use media queries
to target small screens and change the order of the .big
element with the order-property
. Also change the size within the media queries
accordingly:
.flexbox {
display: flex;
flex-wrap: wrap;
}
@media only screen
and (max-width: 576px) {
.flexbox > .big {
order: -1;
width: 100%;
}
.flexbox > .small {
width: calc(100% / 3);
}
}
section {
box-sizing: border-box;
}
/* original CSS */
section {
height: 350px;
width: 20%;
border: 1px solid black;
}
.big {
width: 40%;
}
<div >
<section ></section>
<section ></section>
<section ></section>
<section ></section>
</div>
CodePudding user response:
You could use CSS grid rather than floating the items.
For the wider viewports you could have the columns defined as
1fr 41.6666% 1fr 1fr
The fr units divide up remaining free space, in this case into 3 equal sections.
For the narrower viewports you could set the grid to have 3 equal columns and then put the big element into the first row and the rest into the second row.
* {
margin: 0;
box-sizing: border-box;
}
.container {
display: grid;
grid-template-columns: 1fr 41.6666% 1fr 1fr;
gap: 1vw;
width: 100vw;
height: 350px;
}
section {
border: 1px solid black;
}
@media (max-width: 600px) {
.container {
height: 700px;
grid-template-rows: 1fr 1fr;
grid-template-columns: 1fr 1fr 1fr;
}
.big {
grid-row: 1;
grid-column: 1 / span 3;
}
.small {
grid-row: 2;
}
}
<div >
<section ></section>
<section ></section>
<section ></section>
<section ></section>
</div>