CSS下划线的数字下划线

时间:2014-12-31 00:20:50

标签: javascript html css underline

如何使用css,html或javascript在下划线下方添加一个小数字,如下图所示?

image

2 个答案:

答案 0 :(得分:7)

使用:after:pseudo-element。

可以实现



div {
  font-size: 15px;
  width: 300px;
  line-height: 30px;
}
span {
  position: relative;
}
span:after {
  position: absolute;
  content: '2';
  width: 100%;
  height: 100%;
  top: 100%;
  left: 0;
  border-top: 1px solid black;
  text-align: center;
  font-size: 9px;
  line-height: 15px;
}

<div>over the <span>Triangle, a few months later,</span> another plane disappeared. A ship named the Sandra.</div>
&#13;
&#13;
&#13;


如果您想将width的{​​{1}}设置为响应率百分比单位,则可以通过设置div来避免span中的换行符。

Fiddle

在下面的示例中,white-space: pre已设置为width以证明这一点。

&#13;
&#13;
25%
&#13;
div {
  font-size: 15px;
  width: 25%;
  line-height: 30px;
}
span {
  position: relative;
  white-space: pre;
}
span:after {
  position: absolute;
  content: '2';
  width: 100%;
  height: 100%;
  top: 100%;
  left: 0;
  border-top: 1px solid black;
  text-align: center;
  font-size: 9px;
  line-height: 15px;
}
&#13;
&#13;
&#13;


此外,您可以使用CSS的attr()函数从HTML元素中获取属性值:添加:伪元素。

&#13;
&#13;
<div>over the <span>Triangle, a few months later</span>, another plane disappeared. A ship named the Sandra.</div>
&#13;
div {
  font-size: 15px;
  width: 50%;
  line-height: 30px;
}
span {
  position: relative;
  white-space: pre;
}
span:after {
  position: absolute;
  content: attr(data-num);
  width: 100%;
  height: 100%;
  top: 100%;
  left: 0;
  border-top: 1px solid black;
  text-align: center;
  font-size: 9px;
  line-height: 15px;
}
&#13;
&#13;
&#13;

答案 1 :(得分:2)

使用@chipChocolates答案,如果您不想将下标放入CSS样式块,而是在需要时在正文中使用它们...

div {
  font-size: 15px;
  width: 300px;
  line-height: 30px;
}
span {
  position: relative;
  width: auto;
  height: 15px;
}
span:after {
  position: absolute;
  content: attr(subscript-line);
  width: 100%;
  height: 100%;
  top: 100%;
  left: 0;
  border-top: 1px solid black;
  text-align: center;
  font-size: 10px;
  line-height: 10px;
}
<div>over the <span subscript-line="1">Triangle, a few months later</span>, another plane disappeared. A ship named the Sandra.</div>
<div>over the <span subscript-line="2">Triangle, a few months later</span>, another plane disappeared. A ship named the Sandra.</div>
<div>over the <span subscript-line="3">Triangle, a few months later</span>, another plane disappeared. A ship named the Sandra.</div>