【问题标题】:get text-bottom on same vertical position no matter text size无论文本大小如何,都可以在相同的垂直位置获取文本底部
【发布时间】:2020-12-01 03:51:35
【问题描述】:

我遇到了一个小的 css 问题,我希望将文本的底部放在相同的垂直位置,即使它们的字体大小不同。但显然这不是它的工作方式。实现这一目标的最直接方法是什么?所以我希望左下角和右下角以及左上角和右上角垂直对齐。

<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>

【问题讨论】:

  • 没有指定高度是不可能的。右上角元素不知道左上角元素的高度。底部元素也是如此。如果您可以使用bottom 而不是top 位置,那将是可能的。

标签: html css vertical-alignment


【解决方案1】:

定位是从元素的边缘开始的。您不能真正从内部文本的基线定位,但您可以通过考虑 font-height 来伪造它。 (虽然不同的字体对基线和字体高度的关系有不同的想法,所以如果在每个位置使用不同的字体,这可能不起作用。)

calc() 不是必需的,但在这里用于说明数学。)

.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>

【讨论】:

    猜你喜欢
    • 2014-10-22
    • 2021-08-11
    • 2015-11-15
    • 1970-01-01
    • 1970-01-01
    • 2016-03-06
    • 1970-01-01
    • 1970-01-01
    • 2018-06-25
    相关资源
    最近更新 更多