Reputation: 1571
.container {
display: grid;
place-items: center;
grid-gap: 20px;
height: 200px;
border: 1px solid red;
}
.top {
border: 1px solid blue;
}
.bottom {
border: 1px solid green;
}
<div class="container">
<div class="top">Top Element</div>
<div class="bottom">Bottom Element</div>
</div>
What i am missing to position those booth elements in the middle of the .container next to each other vertically with 20px gap only? Currently they booth are positioned in the center of every grid cell. Sure, I can use simple wrapper and replace grid-gap with some margins. But I would like to have as less CSS and wrapper elements as possible.
Upvotes: 0
Views: 42
Reputation: 12068
You can do it with the align-self: end
& align-self: start
given to grid items:
.container {
display: grid;
place-items: center;
grid-gap: 20px;
height: 200px;
border: 1px solid red;
}
.top {
align-self: end;
border: 1px solid blue;
}
.bottom {
align-self: start;
border: 1px solid green;
}
<div class="container">
<div class="top">Top Element</div>
<div class="bottom">Bottom Element</div>
</div>
Or with the align-content: center
given to the grid container:
.container {
display: grid;
place-items: center;
align-content: center;
/*grid-gap: 20px;*/
height: 200px;
border: 1px solid red;
}
.top {
border: 1px solid blue;
}
.bottom {
border: 1px solid green;
}
<div class="container">
<div>Element</div>
<div class="top">Top Element</div>
<div>Element</div>
<div class="bottom">Bottom Element</div>
<div>Element</div>
</div>
Upvotes: 2
Reputation: 1571
I figured this out this way. Not sure is this the best solution, but will post it.
.container {
display: grid;
place-content: center;
grid-gap: 20px;
height: 400px;
border: 1px solid red;
}
.top {
border: 1px solid blue;
}
.bottom {
border: 1px solid green;
}
<div class="container">
<div class="top">Top Element</div>
<div class="bottom">Bottom Element</div>
</div>
This way I can insert as many child elements as I want. I assume that MS browsers do not support place-items and place-content shorthand so you should use align-content and justify-content instead.
Upvotes: 1
Reputation: 273031
You need to define grid-template-columns
if you want them next to each other
.container {
display: grid;
justify-content: center;
align-items: center;
grid-gap: 20px;
grid-template-columns: repeat(2, max-content);
height: 200px;
border: 1px solid red;
}
.top {
border: 1px solid blue;
}
.bottom {
border: 1px solid green;
}
<div class="container">
<div class="top">Top Element</div>
<div class="bottom">Bottom Element</div>
</div>
Upvotes: 1