html – 如何在基线上定位文本?

PLAYGROUND HERE

HTML:

<div class="first">Hello g World</div>
<div class="second">Hello g World</div>

CSS:

div {
  background-color: rgba(255,0.3); /* For visualization only */
  margin-top: 50px;                       /* For visualization only */
  height: 20px;                           /* This is fixed! */
}

.first {
  font-size: 16px;                        /* This can change */
}

.second {
  font-size: 30px;                        /* This can change */
}

结果:

如何定位文本,使其基线(“Hello”的底部)与粉红色框的底部对齐,即:

有没有办法实现这一点,无论字体大小?

PLAYGROUND HERE

解决方法

搜索…并且搜索之后,我想出了关于如何将文本与元素的基线对齐的非常棒的 tutorial at adobe’s place.

使用假元素

我会建议这个,但看看下面的所有故事(从.strut元素到单个伪元素的道路):

div {
  width: 400px;
  height: 100px;
}
.first {
  font-size: 24px;
  background-color: #9BBCE3;
}
.first::after {
  content: "";
  height: 100%;
  display: inline-block;
}
<div>
  <div class="first">Hello g World / With font-size: 24px</div>
</div>

使用额外的.STRUT元素

>场景和规则

规则1(较大的字体):我们希望div的高度是固定的.例如20px.因此,font-size必须等于或小于.height值才能工作.通常,

〜前面的尺寸必须与固定高度相等或相当.它适用于所有尺寸且价格低廉的尺寸

场景1:假设我们的字体大于本案例的20px.

见它在行动:http://jsfiddle.net/csdtesting/pvw5xhku/

div.forall {
  width: 700px;
  height: 48px;
  border: thin black solid;
  background-color: #9BBCE3;
  margin-top: 20px;
}
.inText {
  font-size: 48px;
  line-height: 48px;
}
.inText3 {
  font-size: 22px;
  line-height: 22px;
}
.strut {
  height: 48px;
  display: inline-block;
}
<div class="forall">
  <div class="inText">Hello g World /With font-size 46px
    <div class="strut"></div>
  </div>
</div>
<div class="forall">
  <div class="inText2">Hello g World /With font-size 32px
    <div class="strut"></div>
  </div>
</div>
<div class="forall">
  <div class="inText3">Hello g World /With font-size 32px
    <div class="strut"></div>
  </div>
</div>

>解释

关于这个实现的所有魔术都是关于.strut元素的.这是一个带有display:inline-block;属性
我想知道……又是什么?!

支柱的基线位于其下边缘处,这在这种情况下仅由支柱的高度确定.如果字母跨度的行高小于支柱的高度,则字母的基线将移动以匹配!难以置信的!

>主要实施

见它在行动:http://jsfiddle.net/csdtesting/bm2yz3ec/

div.forall {
  width: 300px;
  height: 20px;
  border: thin black solid;
  background-color: #9BBCE3;
  margin: 10px;
}
.inText {
  font-size: 20px;
  line-height: 20px;
}
.intext2 {
  font-size: 9px;
  line-height: 9px;
}
.strut {
  height: 20px;
  display: inline-block;
}
<div class="forall">
  <div class="inText">Hello g World /With font-size 20px
    <div class="strut"></div>
  </div>
</div>
<div class="forall">
  <div>Hello g World / Without font-size
    <div class="strut"></div>
  </div>
</div>
<div class="forall">
  <div class="intext2">Hello g World / with font-size:9px
    <div class="strut"></div>
  </div>
</div>

相关文章

vue阻止冒泡事件 阻止点击事件的执行 &lt;div @click=&a...
尝试过使用网友说的API接口获取 找到的都是失效了 暂时就使用...
后台我拿的数据是这样的格式: [ {id:1 , parentId: 0, name:...
JAVA下载文件防重复点击,防止多次下载请求,Cookie方式快速简...
Mip是什么意思以及作用有哪些