Search code examples
htmlcssalignmentvertical-alignmentbaseline

Align text baseline to bottom of div


I am trying to align the baseline of some text in a div to the very bottom edge of said div (such that characters like g and j would actually overflow the div)

I can only seem to align the bottom edge of the text element to the bottom edge of the div. I have tried to use vertical-align with values baseline and bottom on the inner and outer element, but without success.

div {
  height: 80px;
  width: 300px;
  background: #ff5;
  position: relative;
}

span {
  font-size: 30px;
  position: absolute;
  left: 0;
  bottom: 0;
}
<div>
  <span>
  TEST gjp ABC
  </span>
</div>

I also want to be able to offset the baseline from the bottom of the div (e.g. bottom: 10px; positions the baseline of the text 10px from the bottom edge of the div).

Edit: I should also mention that I want to keep the position: absolute; property on the span element, because I want to freely position multiple of those in the parent div.

For example, here, A's baseline should be at the bottom edge of the div, B's should be 10px above it and C's 20px:

div {
  height: 80px;
  width: 300px;
  background: #ff5;
  position: relative;
}

span {
  font-size: 30px;
  position: absolute;
  left: 0;
  bottom: 0;
}
<div>
  <span style="left: 0px; bottom: 0px;">
  A
  </span>
  <span style="left: 50px; bottom: 10px;">
  B
  </span>
  <span style="left: 100px; bottom: 20px;">
  C
  </span>
</div>


Solution

  • Add a ::before pseudo element with 100% height and display: inline-block; and use it to vertically align the <span> to the baseline:

    div {
      height: 80px;
      width: 300px;
      background: #ff5;
      position: relative;
    }
    
    div::before {
      display: inline-block;
      height: 100%;
      content: '';
    }
    
    span {
      font-size: 30px;
      vertical-align: baseline;
    }
    <div>
      <span>TEST gjp ABC</span>
    </div>

    You can apply the same idea to the span itself, but you'll have to state the height of the span:

    div {
      height: 80px;
      width: 300px;
      background: #ff5;
      position: relative;
    }
    
    span {
      display: inline-block;
      font-size: 30px;
      position: absolute;
      left: 0;
      bottom: 0;
      height: 1em;
      background: red;
    }
    
    span::before {
      display: inline-block;  
      height: 100%;
      vertical-align: baseline;
      content: '';
    }
    <div>
      <span style="left: 0px; bottom: 0px;">gjp</span>
      <span style="left: 50px; bottom: 10px;">gjp</span>
      <span style="left: 100px; bottom: 20px;">gjp</span>
    </div>