PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, November 16, 2022

[FIXED] How do I do a single row, vertically centered, layout in CSS grid?

 November 16, 2022     css, css-grid, vertical-alignment     No comments   

Issue

I am trying to do a single row, vertically centered layout using CSS grid. Here's a rough sketch:

enter image description here

Note:

  • I have a single row of items
  • The items are (probably) going to be the same width
  • I do not know many items I have (so I don't want to have to say '200px' eighty times)
  • The items are of different heights, but need to be vertically centered

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?


Solution

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 row
  • align-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>



Answered By - mikemaccana
Answer Checked By - Katrina (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing