I want to display up to two items in a CSS grid (using subgrids to align content within the items, hence the need for grids specifically). Sometimes there’s just one item to display though and in those cases I’d like to have the CSS just display the one column and center it.
.content {
display: flex;
flex-direction: column;
align-items: center;
width: 100%;
}
.cards {
display: grid;
grid-template-columns: repeat(2, 300px);
column-gap: 8px;
}
.product-card {
background-color: teal;
}
<div class="content">
The below looks correct
<div class="cards">
<div class="product-card">Product 1</div>
<div class="product-card">Product 2</div>
</div>
This one is funny though, I'd like the product to be centered rather than affording space to an unused column.
<div class="cards">
<div class="product-card">Product 1</div>
</div>
</div>
Is there a way to use these 300px wide columns, but have the number of columns be varied (between one and two in my case) based on how many elements are actually present?
2
Answers
Use the following selector to select
.cards
that only have one child..cards:has(:only-child) { grid-template-columns: repeat(1, 300px); }
Style them to only have one column.
Note: compatibility of the :has pseudo-selector.
Here we target
.cards
which contains 2.product-card
neighbors only :