Search code examples
cssalignmentvertical-alignment

How can I align an element (h3) at the bottom of a div?


I have two headers (h2 and h3) inside a div, and I want to align the second (h3) to the bottom of the div right above the bottom-border. I'm working with some inherited code, and the height is responsive, so can't be set. Here's the codepen. Here's the HTML:

 <div id="toc-texts">
  <div class="toc-entry">
    <h2>Title 1 That is Actually Really Long</h2>
    <h3 class="author">Author Name 1</h3>    
  </div>
   <div class="toc-entry">
    <h2>Title 2</h2>
    <h3 class="author">Author Name 2</h3>    
  </div>
   <div class="toc-entry">
    <h2>Title 3</h2>
    <h3 class="author">Author Name 3</h3>    
  </div>
 </div>

And here's the css I have so far:

div#toc-texts {
    display: inline;
  } 

div.toc-entry {
  text-align: center;
  border-bottom: 2px solid blue;
}

@media (min-width: 30em) {
  div#toc-texts {
    margin-bottom: 4rem;
    display: inline-grid;
    grid-template-columns: 9rem 9rem 9rem;
    grid-gap: 4em;
  }
  
}

How can I align the h3 to the bottom of the div in a way that works on all browsers and on mobile?


Solution

  • Use a flexbox column.

    Push the h3 to the bottom with margin-top:auto and then align right.

    div#toc-texts {
      display: inline;
    }
    
    div.toc-entry {
      text-align: center;
      border-bottom: 2px solid blue;
      display: flex;
      flex-direction: column;
    }
    
    h3.author {
      font-size: .9em;
      font-style: italic;
      margin-top: auto;
      text-align: right;
    }
    
    @media (min-width: 30em) {
      div#toc-texts {
        margin-bottom: 4rem;
        display: inline-grid;
        grid-template-columns: 9rem 9rem 9rem;
        grid-gap: 4em;
      }
    }
    <div id="toc-texts">
      <div class="toc-entry">
        <h2>Title 1 That is Actually Really Long</h2>
        <h3 class="author">Author Name 1</h3>
      </div>
      <div class="toc-entry">
        <h2>Title 2</h2>
        <h3 class="author">Author Name 2</h3>
      </div>
      <div class="toc-entry">
        <h2>Title 3</h2>
        <h3 class="author">Author Name 3</h3>
      </div>
    </div>