skip to Main Content

I have a grid with two columns. The second column has a larger font size:

enter image description here

.container {
  display: grid;
  grid-template-columns: max-content 1fr;
  gap: 0.5rem;
}

.text1 {
  color: #fff;
  background-color: #000;
}

.text2 {
  font-size: 3.75rem;
}
<div class="container">
  <div class="text1">text1</div>
  <div class="text2">text2</div>
</div>

I wanted to align the texts to the baseline so I added align-items: baseline; to .container and this happened:

enter image description here

The texts are aligned correctly but the black background doesn’t take the whole grid block. How can I keep the text1 container stretched while aligning its content to baseline?

I’ve tried these but none of them worked:

  1. adding height: 100% to .text1
  2. adding align-self: stretch and align-content: baseline to .text1
  3. a wrapper div for the background and a span for the content and setting align-self: baseline for the span.

3

Answers


  1. If you don’t want to use a table, this answer might point you in the correct direction.

    If you don’t mind using display: table, you can use the vertical-align property, as shown here.

    .container {
      display: table;
      grid-template-columns: max-content 1fr;
      gap: 0.5rem;
    }
    
    .text1 {
      display: table-cell;
      color: #fff;
      background-color: #000;
      vertical-align: bottom;
    }
    
    .text2 {
      font-size: 3.75rem;
    }
    <div class="container">
      <div class="text1">text1</div>
      <div class="text2">text2</div>
    </div>
    Login or Signup to reply.
  2. You can try to align text item by flex:

    .container {
        display: grid;
        grid-template-columns: max-content 1fr;
        gap: 0.5rem;
        align-items: baseline;
    }
    
    .text1 {
        color: #fff;
        background-color: #000;
        height: 100%;
        display: flex;
        align-items: last baseline;
    }
    
    .text2 {
        font-size: 3.75rem;
        align-self: center;
    }
    <div class="container">
        <div class="text1">text1</div>
        <div class="text2">text2</div>
    </div>
    Login or Signup to reply.
  3. I used align-items:self-end , display:flex and line-height attributes to align the texts same level.

    .container {
     display: grid;
     grid-template-columns: repeat(auto-fill, minmax( max-content, 0px));
     grid-gap: 1rem;
    }
    .text1 {
     color: #fff;
     background-color: #000;
     align-items:self-end;
     display:flex;
     height:100px;
     padding:25px 25px 0px 25px;
     line-height:0.9;
    
    }
    .text2 {
     color: #000;
     display: flex;
     align-items:self-end;
     font-size: 3.25rem;
     line-height: 0.7;
    }
    <div class="container">
     <div class="text1">text1</div>
     <div class="text2">text2</div> 
    </div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search