I have a series of images that are fetched from a database, and when three or more images are added it visually shows the three columns.
When less than three images are present, because I'm using display: grid;
it is currently justified to the left of the parent container (in the code example I've just used red boxes to represent the images).
Is there anyway of having it so that when one or two images are present these are justified to the centre of the parent element. I appreciate I could use javascript to detect how many images are present and if it is less than three, add a class and change the wrapper to display: flex
, but I wondered if such a layout was possible with CSS only?
Due to the nature of the layout I do need to use CSS Grid when more than three images are present.
Note: I've commented out two of the red boxes in the HTML to show the initial 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 >
<div ></div>
<!-- <div ></div>
<div ></div> -->
</div>
CodePudding user response:
using auto
instead of fr
and using align-content
solve your problem.
body {
display: flex;
justify-content: center;
margin: 0
width: 100%;
height: 100vh;
}
.wrapper {
display: grid;
grid-template-columns: auto auto auto;
align-content : start;
grid-gap: 1rem;
max-width: 1250px;
}
.box {
width: 200px;
height: 200px;
background: red;
}
<div >
<div ></div>
<!-- <div ></div>
<div ></div> -->
</div>
CodePudding user response:
If you only wish to center the boxes, you can do it by using flex easily.
body {
margin: 0
}
.wrapper {
display: flex;
justify-content: center;
}
.box {
width: 200px;
height: 200px;
margin: 10px;
}
.box-1{
background: red;
}
.box-2{
background: green;
}
.box-3{
background: blue;
}
<div >
<div ></div>
<!-- <div ></div> -->
<!-- <div ></div> -->
</div>