I need to create 2 columns layout which will align items in the second column vertically if the number of items is odd. Can't realize how to do it. A number of items are unknown.
.container {
border: 1px solid red;
display: grid;
grid-auto-rows: 1fr;
grid-template-rows: auto;
grid-template-columns: 1fr 1fr;
}
.item {
border: 1px dashed blue;
box-sizing: border-box;
height: 50px;
}
<div >
<div >1</div>
<div >2</div>
<div >3</div>
<div >4</div>
<div >5</div>
<div >6</div>
<div >7</div>
</div>
Here is a link to Codepen if someone prefers this editor. https://codepen.io/anatoly314/pen/bGvRmEa
Thank you!
CodePudding user response:
A hacky solution to use with caution:
.container {
border: 1px solid red;
display: grid;
grid-auto-rows: 1fr;
grid-template-rows: auto;
grid-template-columns: 1fr 1fr;
margin: 5px;
}
.item {
border: 1px dashed blue;
box-sizing: border-box;
height: 50px;
}
/*
translate all the elements in the second column
when we have odd elements
*/
.item:first-child:nth-last-child(odd) ~ .item:nth-child(even) {
transform:translateY(50%);
}
<div >
<div >1</div>
<div >2</div>
<div >3</div>
<div >4</div>
<div >5</div>
<div >6</div>
<div >7</div>
</div>
<div >
<div >1</div>
<div >2</div>
<div >3</div>
<div >4</div>
<div >5</div>
<div >6</div>
</div>
Also like below if you want to fill all the space:
.container {
border: 1px solid red;
display: grid;
grid-auto-rows: 1fr;
grid-template-rows: auto;
grid-template-columns: 1fr 1fr;
margin: 5px;
}
.item {
border: 1px dashed blue;
box-sizing: border-box;
height: 50px;
}
.item:first-child:nth-last-child(odd) ~ .item:nth-child(even) {
transform:translateY(50%);
}
/* no transform for the fist item in the second column */
.item:first-child:nth-last-child(odd) .item:nth-child(even) {
transform: none;
}
/* make first and last item in second column bigger */
.item:first-child:nth-last-child(odd) .item:nth-child(even),
.item:nth-last-child(2):nth-child(even){
height: 150%;
}
/* smaller transform for the last item since it's bigger */
.item:nth-last-child(2):nth-child(even) {
transform:translateY(33%)!important;
}
<div >
<div >1</div>
<div >2</div>
<div >3</div>
<div >4</div>
<div >5</div>
<div >6</div>
<div >7</div>
</div>
<div >
<div >1</div>
<div >2</div>
<div >3</div>
<div >4</div>
<div >5</div>
<div >6</div>
<div >7</div>
<div >8</div>
<div >9</div>
<div >10</div>
<div >11</div>
</div>