Issue
I am trying to build a CSS grid
I do not want to have space between item2 and item3, and want these items to be aligned on top of the container.
Is this possible with CSS only, without modifying the HTML structure?
.grid-container {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 10px;
align-items: start;
}
.item1,
.item2,
.item3 {
border: 1px solid black;
}
.item1 {
grid-column: span 1;
grid-row: span 2;
}
.item1 img {
width: 80px;
height: 115px;
}
.item2,
.item3 {
grid-column: span 1;
grid-row: span 1;
}
<div class="grid-container">
<div class="item1">
<img src="https://dummyimage.com/80x115/000/fff">
</div>
<div class="item2">Element 2</div>
<div class="item3">Element 3</div>
</div>
Solution
Add these lines to your .grid-container
style:
grid-template-rows: 0fr 1fr;
row-gap: 0;
Preview:
.grid-container {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 10px;
align-items: start;
grid-template-rows: 0fr 1fr;
row-gap: 0;
}
.item1,
.item2,
.item3 {
border: 1px solid black;
}
.item1 {
grid-column: span 1;
grid-row: span 2;
}
.item1 img {
width: 80px;
height: 115px;
}
.item2,
.item3 {
grid-column: span 1;
grid-row: span 1;
}
<div class="grid-container">
<div class="item1">
<img src="https://dummyimage.com/80x115/000/fff">
</div>
<div class="item2">Element 2</div>
<div class="item3">Element 3</div>
</div>
Update:
If you need to add more elements, you can change the HTML structure and/or use pseudo element like :before
and/or :after
.
Don't forget to update your grid template. See example below:
.grid-container {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 10px;
align-items: start;
grid-template-rows: 0fr 0fr 1fr;
row-gap: 0;
}
.item1,
.item2,
.item3,
.item4 {
border: 1px solid black;
}
.item1 {
grid-column: span 1;
grid-row: span 3;
}
.item1 img {
width: 80px;
height: 115px;
}
.item2,
.item3,
.item4 {
grid-column: span 1;
grid-row: span 1;
}
<div class="grid-container">
<div class="item1">
<img src="https://dummyimage.com/80x115/000/fff">
</div>
<div class="item2">Element 2</div>
<div class="item3">Element 3</div>
<div class="item4">Element 4</div>
</div>
If you need more flexible layout for unpredictable elements, try to use flexbox instead of grid.
Answered By - Faris Han
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.