按基线对齐块级元素和段落元素

时间:2012-05-21 19:43:12

标签: css

我试图通过基线将标题与文本正文对齐,但这似乎令人惊讶地难以理解。我一直在玩弄不同的方法,但似乎无法找到完美的解决方案。以下是我所追求的一个例子:

example

<h2>XxMmxX</h2>
<p class="right">
    I saw for the first time the earth's shape. I could easily see the shores of continents, islands, great rivers, folds of the terrain, large bodies of water. The horizon is dark blue, smoothly turning to black. . . the feelings which filled me I can express with one word—joy.
</p>

风格:

h2 {
    position: relative;
    font-size: 24px;
    line-height: 40px;
    text-align: right;
    width: 190px;
    top: 30px;
}
.right {
    margin-left: 200px;
    font-size: 14px;
    line-height: 20px;
}

我希望'XxMmxX'的基线与文本的基线保持一致。

一些注意事项:

  • 标题右对齐且具有固定宽度
  • 标题使用比body更大的字体大小
  • 我希望它们完全对齐,这意味着不仅要设置某个px的顶部并让它几乎对齐。 (此页面将被打印,这肯定会引人注目)

4 个答案:

答案 0 :(得分:3)

尝试使用表格,然后使用vertical-align: baseline;

答案 1 :(得分:0)

这是另一个没有表格的解决方案: 首先,我使用<div>代替<p>

<h2 class="left">XxMmxX</h2>

<div class="right">
    I saw for the first time the earth's shape. I could easily see the shores of continents, islands, great rivers, folds of the terrain, large bodies of water. The horizon is dark blue, smoothly turning to black. . . the feelings which filled me I can express with one word—joy.
</div>

我使用float<div>放在<h2>旁边。通过设置已知字体大小来完成对齐技巧,例如1em<div>1.5em<h2>。这样,您需要将<div>向下移动已知数量,在本例中为0.5em。向下移动是使用position/top(您也可以使用margin-top)。这是:

.left {
  float: left;
  font-size: 1.5em;

}

.right {
  font-size: 1em;
  float: left;
  width: 20em;  
  position: relative;
  top: 0.5em;
  margin-left: 10px;
}

答案 2 :(得分:0)

我可能会有一些接近的东西。这是jsfiddle

HTML:

<span class="textblock">
  <h2>XxMmxXx</h2>

  <span class="right">
    I saw for the first time the earth's shape. I could easily see the shores of continents, islands, great rivers, folds of the terrain, large bodies of water. The horizon is dark blue, smoothly turning to black. . . the feelings which filled me I can express with one word—joy.
  </span>

</span>

CSS:

.textblock {
  float: left;
  line-height: 1em;
}

h2 {
  font-size: 1.5em;
  display: inline-block;
}

.right {
  display: inline-block;
  font-size: 1em;
  width: 15em;
  vertical-align: text-top;
  margin-left: 30px;
}

似乎vertical-align: text-top可能是您想要的,但它需要一切都是内联的。结合display:inline-block,您可以获得接近您需要的东西。你可能不得不调整.right类的宽度和边距来调整你的布局。

希望有所帮助。

答案 3 :(得分:0)

您不必使用表格布局,也不必使用vertical align。将两个元素设置为使用相同的line-height并对齐元素的顶部。如果您对将文本放在基线上感到挑剔,请使用position:relative; and top:FOOpx上下移动文本。

相关问题