Search code examples
htmlcssreactjscss-grid

Center text to bottom in grid area


I'm a bit new to HTML and CSS but I'm trying to learn grids. I have a background in WPF which heavily uses grids. It's mostly straightforward but I'm confused on how to align to the bottom of it's area.

AccountBar.js

<div className={styles.container}>
    <img className={styles.avatar} style={{backgroundImage: `url(${profileURL})`}}></img>
    <text className={styles.username}>Username</text>
    <text className={styles.discriminator}>#1337</text>
</div>

style.module.css

.container {
    display: grid;
    grid-template-areas:
    'avatar username'
    'avatar discriminator';
}

.avatar {
    grid-area: avatar;
    background-image: url('https://tenor.com/view/pigeon-pidgeon-fire-eyes-burn-gif-24781901.gif');
    background-size: cover;
    border-radius: 50%;
    width: 100px;
    height: 100px;
    border: 3px solid #591496;
}

.username {
    grid-area: username;
    color: white;
}

.discriminator {
    grid-area: discriminator;
    color: white;
}

The result looks like so, but I'm trying to align "Username" to the bottom of it's cell.


Solution

  • I think your problem is not from the grid but from element alignment. You can add margin-top: auto; (adding a top margin to cover all upper space and push your text to the bottom) to .username which would help you do the trick.

    .container {
      display: grid;
      grid-template-areas:
        'avatar username'
        'avatar discriminator';
      background-color: #ccc; /*For testing*/
    }
    
    .avatar {
      grid-area: avatar;
      background-image: url('https://tenor.com/view/pigeon-pidgeon-fire-eyes-burn-gif-24781901.gif');
      background-size: cover;
      border-radius: 50%;
      width: 100px;
      height: 100px;
      border: 3px solid #591496;
    }
    
    .username {
      grid-area: username;
      color: white;
      margin-top: auto; /*The change is here*/
    }
    
    .discriminator {
      grid-area: discriminator;
      color: white;
    }
    <div class="container">
        <img class="avatar" style="background-image: url('https://cdn.pixabay.com/photo/2015/04/23/22/00/tree-736885__480.jpg');"/>
        <text class="username">Username</text>
        <text class="discriminator">#1337</text>
    </div>