Reputation: 74
I'm building a services page with CSS grid, I want to flip every other row. So the second row has the image on the left and the text on the right. The third one should be the same as the first one, and so on. What would be the simplest solution?
Thanks!
Link to Codepen
.servicios-container {}
.servicios-card {
margin: 100px 200px;
display: grid;
align-items: center;
grid-template-columns: 1.5fr 1fr;
grid-gap: 140px;
}
.servicios-card img {
width: 100%;
border-radius: 50px;
}
.servicios-texto h2 {
font-size: 46px;
}
.servicios-texto p {
font-size: 20px;
}
<div class="servicios-container">
<div class="servicios-card">
<div class="servicios-texto">
<h2>Edición de audio</h2>
<p>Lorem ipsum, dolor sit amet consectetur adipisicing elit. Dignissimos laboriosam, nobis quidem eius sit excepturi, minima modi cum, incidunt quo repellat odio adipisci reiciendis quis earum aliquam optio consectetur fugiat.</p>
<form action="#">
<button class="contacto-btn m-top" type="submit">Mas información</button>
</form>
</div>
<img src="https://placeimg.com/450/300/tech" />
</div>
<!-- this card should have the img on the left-side -->
<div class="servicios-card">
<img src="img\Estudio-de-grabación-servicios-Solistas.jpg" alt="">
</div>
<!-- this card should have the img on the right-side as the first card -->
<div class="servicios-card">
<img src="img\Estudio-de-grabación-servicios-Video.jpg" alt="">
</div>
</div>
Upvotes: 1
Views: 1875
Reputation: 431
Use nth-child(even) pseudo-selector to target all even elements and update the columns of its children
.servicios-card:nth-child(even) .servicios-texto {
grid-column: 2;
}
.servicios-card:nth-child(even) img {
grid-column: 1;
grid-row: 1;
}
In your case since you have uneven columns, you will also have to update your grid for every even element
.servicios-card:nth-child(even) {
grid-template-columns: 1fr 1.5fr;
}
Edit: There is a more clever solution.
Using grid template areas would make it cleaner
Update your wrapper element to something like this
.servicios-card {
margin: 100px 200px;
display: grid;
align-items: center;
grid-template-columns: 1.5fr 1fr;
grid-template-areas:
"img text";
grid-gap: 140px;
}
Here you're making areas for your child elements so you only have to switch the areas and columns size on every even element.
Assign the children to your grid areas
.servicios-card img {
grid-area: img;
}
.servicios-texto {
grid-area: text;
}
Then, target even elements to do the magic.
.servicios-card:nth-child(even) {
grid-template-areas:
"text img";
grid-template-columns: 1fr 1.5fr
}
Upvotes: 1