Search code examples
htmlcssvertical-alignment

get text-bottom on same vertical position no matter text size


I got this small css problem where I expected to get the bottom of the text on the same vertical position even though they are in different font sizes. But apperantly that is not how it works. What is the most straightforward way of achieving this? So I want bottom left and right to be vertically aligned as well as top left and top right.

<html>
<head>
<style>
.container {
  position: relative;
  width: 300px;
  height: 100px;
}
.topright {
  position: absolute;
  top: 20px;
  right: 16px;
  font-size: 8px;
}
.topleft {
  position: absolute;
  top: 20px;
  left: 16px;
  font-size: 28px;
}
.bottomright {
  position: absolute;
  top: 100px;
  right: 16px;
  font-size: 28px;
}
.bottomleft {
  position: absolute;
  top: 100px;
  left: 16px;
  font-size: 18px;
}
</style>
</head>
<body>
<div class="container">
  <div class="topleft">Top Left</div>
  <div class="topright">Top Right</div>
  <div class="bottomleft">Bottom Left</div>
  <div class="bottomright">Bottom Right</div>
</div>
</body>
</html>


Solution

  • Positioning is from the edges of the element. You can't really position from the inner text's baseline but you can fake it by taking the font-height into account. (Though different fonts have different ideas of how baseline and font-height are related so this may not work if using different fonts in each spot.)

    (calc() isn't necessary but is used here to illustrate the math.)

    .container {
      position: relative;
      width: 300px;
      height: 100px;
    }
    .topright {
      position: absolute;
      top: calc(20px - 8px);
      right: 16px;
      font-size: 8px;
    }
    .topleft {
      position: absolute;
      top: calc(20px - 28px);
      left: 16px;
      font-size: 28px;
    }
    .bottomright {
      position: absolute;
      top: calc(100px - 28px);
      right: 16px;
      font-size: 28px;
    }
    .bottomleft {
      position: absolute;
      top: calc(100px - 18px);
      left: 16px;
      font-size: 18px;
    }
    <div class="container">
      <div class="topleft">Top Left</div>
      <div class="topright">Top Right</div>
      <div class="bottomleft">Bottom Left</div>
      <div class="bottomright">Bottom Right</div>
    </div>