Search code examples
javascripthtmlcssunderline

CSS underline text with number below line


How can I underline text and add a small number underneath the underline like in this image using css, html, or javascript?

image


Solution

  • This is possible using :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>


    If you want to set the width of the div to percentage units for responsiveness, you could avoid line break in span by setting white-space: pre.

    Fiddle

    In the example below, the width has been set to 25% to demonstrate this.

    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;
    }
    <div>over the <span>Triangle, a few months later</span>, another plane disappeared. A ship named the Sandra.</div>


    Also, you could use CSS's attr() function to fetch attribute values from the HTML element the :pseudo-element is added on.

    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;
    }
    <div>over the <span data-num="2">Triangle, a few months later</span>, another plane disappeared. A ship named the Sandra.</div>