Reputation: 123138
I am trying to do a single row, vertically centered layout using CSS grid. Here's a rough sketch:
Note:
HTML:
<div class="wrapper">
<div class="box a">A</div>
<div class="box b">B</div>
<div class="box c">C</div>
</div>
CSS:
.wrapper {
display: grid;
grid-gap: 10px;
grid-auto-columns: 200px;
background-color: #fff;
color: #444;
.box {
background-color: #444;
color: #fff;
border-radius: 5px;
padding: 20px;
font-size: 150%;
}
}
I've tried this ibut it really wants to do multiple rows instead of multiple columns on one row.
Can I do a single row, vertically centered layout in CSS grid? If so, how?
Upvotes: 24
Views: 67257
Reputation: 123138
Here's a working example. It works just as well as the other answer, but uses different CSS to avoid setting the grid row explicitly. Click 'Run' below:
grid-auto-flow: column;
makes items flow across columns, ie into a single rowalign-self: center;
does vertical centering.wrapper {
display: grid;
grid-auto-flow: column;
}
.box {
align-self: center;
}
/* Additional styles below */
.wrapper {
grid-gap: 10px;
background-color: #fff;
color: #444;
}
.box {
background-color: #444;
color: #fff;
border-radius: 5px;
padding: 20px;
font-size: 150%;
}
body {
margin: 40px;
}
.box.a {
height: 200px;
}
.box.b {
height: 20px;
}
.box.c {
height: 120px;
}
<div class="wrapper">
<div class="box a">A</div>
<div class="box b">B</div>
<div class="box c">C</div>
<div class="box c">D</div>
</div>
Upvotes: 58
Reputation: 371133
To force all items into a single row, set them to grid-row: 1
.
To center the items, set the container to align-items: center
, or each item to align-self: center
. (align-self
inherits the align-items
value by default).
.wrapper {
display: grid;
align-items: center; /* new */
}
.box {
grid-row: 1; /* new */
}
.box.a { height: 200px; }
.box.b { height: 20px; }
.box.c { height: 120px; }
.box.d { height: 50px; }
/* non-essential decorative styles */
.wrapper {
grid-gap: 10px;
background-color: #fff;
color: #444;
}
.box {
background-color: #444;
color: #fff;
border-radius: 5px;
padding: 20px;
font-size: 150%;
}
body {
margin: 40px;
}
<div class="wrapper">
<div class="box a">A</div>
<div class="box b">B</div>
<div class="box c">C</div>
<div class="box d">D</div>
</div>
Upvotes: 8