Squideyes Squideyes - 6 months ago 24
HTML Question

Switch nth-child with media queries

I have the following simple grid using

nth-child
:



.grid section {
float: left;
width: 32%;
background: #ccc;
margin: 0 2% 2% 0;
}
.grid section:nth-child(3n+3) {
margin: 0 0 2% 0;
}
@media screen and (max-width: 600px) {
.grid section {
width: 48%;
margin: 0 2% 2% 0;
}
.grid section:nth-child(3n+3) {
margin: auto;
}
.grid section:nth-child(even) {
margin: 0 0 2% 0;
}
}

<div class="grid">

<section class="box">
<p>I'm a box</p>
</section>

<section class="box">
<p>I'm a box</p>
</section>

<section class="box">
<p>I'm a box</p>
</section>

<section class="box">
<p>I'm a box</p>
</section>

<section class="box">
<p>I'm a box</p>
</section>

<section class="box">
<p>I'm a box</p>
</section>

</div>





On the desktop version of the code, the grid displays 3 boxes in a row.

When the screen size reaches 600px, it drops down to 2 boxes in a row. Is there a way I can switch off
nth-child(3n+3)
within the media query?

Answer

Simply add the nth-child rule in a query that turns in on on screens above 600px

Like so:

@media screen and (min-width: 600px) {
  .grid section:nth-child(3n+3) {
    margin: 0 0 2% 0;
  }
}
Comments