skip to Main Content

I have a set of links that need to be truncated. I know that text.overflow: elipsis on anchors can be troublesome, but here’s my question:

How can I make anchor text-decoration: underline follow the width of the truncated anchor?

As you can see, the three dots are positioned outside the link underline.

I also tried to add the truncation to the inner span of each link, but it makes the link’s underline disappear.

How can I solve this?

a {
  text-decoration: underline;
  width: 150px;
  display: inline-block;
  white-space: nowrap;
  text-overflow: ellipsis;
  overflow: hidden;
}
<ul>
  <li>
    <a href="#"><span class="link-text">Menu item</span></a>
  </li>
  <li>
    <a href="#"><span class="link-text">Very long menu item that needs to be truncated</span></a>
  </li>
  <li>
    <a href="#"><span class="link-text">Menu item</span></a>
  </li>
</ul>

2

Answers


  1. A pseudo-element on the span, suitable positioned, would not be a complete replacement for text-decoration but it would be a functional equivalent.

    a {
      width: 150px;
      display: inline-block;
      white-space: nowrap;
      text-overflow: ellipsis;
      overflow: hidden;
      text-decoration: none;
      padding-bottom: .05em;
    }
    
    span {
      position: relative;
    }
    
    span:after {
      content: "";
      width: 100%;
      height: 1px;
      background: blue;
      position: absolute;
      bottom: 0em;
      left: 0;
    }
    
    ul {
      list-style: none;
    }
    <ul>
      <li>
        <a href="#"><span class="link-text">Menu item</span></a>
      </li>
      <li>
        <a href="#"><span class="link-text">Very long menu item that needs to be truncated</span></a>
      </li>
      <li>
        <a href="#"><span class="link-text">Menu item</span></a>
      </li>
    </ul>
    Login or Signup to reply.
  2. You can simply add a border-bottom to the anchor. However you should use max-width instead of width so the border does nto streatch to the full 150px in every case.

    a {
      text-decoration: none;
      max-width: 150px;
      display: inline-block;
      white-space: nowrap;
      text-overflow: ellipsis;
      overflow: hidden;
      border-bottom: 1px solid blue;
    }
    <ul>
      <li>
        <a href="#"><span class="link-text">Menu item</span></a>
      </li>
      <li>
        <a href="#"><span class="link-text">Very long menu item that needs to be truncated</span></a>
      </li>
      <li>
        <a href="#"><span class="link-text">Menu item</span></a>
      </li>
    </ul>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search