In my current setup, a series of images are fetched from a database. When three or more images are added, it visually displays in three columns.
However, if there are fewer than three images, they align to the left within the parent container due to the display: grid;
property I am using (as demonstrated by the red boxes in the code example).
I am wondering if it is possible to have one or two images centered within the parent element instead. While I could use JavaScript to detect the number of images and adjust the layout accordingly by changing the wrapper to display: flex
, I am curious if there is a CSS-only solution for this scenario.
It's important to note that when there are more than three images present, I must stick with CSS Grid for the layout.
Note: I've commented out two of the red boxes in the HTML to illustrate the issue when only one red box is present.
Codepen: https://codepen.io/anna_paul/pen/xxXrVJQ
body {
display: flex;
justify-content: center;
margin: 0
width: 100%;
height: 100vh;
}
.wrapper {
display: grid;
grid-template-columns: 1fr 1fr 1fr;
grid-gap: 1rem;
max-width: 1250px;
}
.box {
width: 200px;
height: 200px;
background: red;
}
<div class="wrapper">
<div class="box"></div>
<!-- <div class="box"></div>
<div class="box"></div> -->
</div>