skip to Main Content
.util-truncate {
  max-width: 100%;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

a {
  text-decoration: none;
}

a:focus {
  box-shadow: 0 0 0 3px blue;
  text-decoration: underline;
}

a:focus-visible {
  outline: 0;
}
<div class="util-truncate">
  <a href="#">This is a long link that will be truncated. This is a long link that will be truncated. This is a long link that will be truncated.</a>
</div>

Problem:

I am trying to apply a ring using box-shadow over the anchor element on focus. But because of the overflow hidden property on parent, the focus style is getting cut-off. As truncate is a utility class I cannot update any of it styles. Is there a way we could display the desired focus style properly for anchor element with only using CSS?

Following are the approaches I tried on anchor focus state,

  1. box-shadow
  2. outline (with offset)
  3. box-shadow with z-index
  4. box-shadow with inset (this approach is a bit close to expected output but not exact)
  5. Using before/after pseudo selector

Output:

enter image description here

2

Answers


  1. Increase the line-height and consider an inset box-shadow

    .util-truncate {
      max-width: 100%;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
    
    a {
      text-decoration: none;
      line-height: 1.4;
      padding: 2px;
    }
    
    a:focus {
      box-shadow: 0 0 0 2px blue inset;
    }
    
    a:focus-visible {
      outline: 0;
    }
    <div class="util-truncate">
      <a href="#">This is a long link that will be truncated. This is a long link that will be truncated. This is a long link that will be truncated.</a>
    </div>
    Login or Signup to reply.
  2. Rather than cutting off the rendering, just limit the width of the a element. You don’t even need a container div for that, just a display: inline-block to make sure it responds to max-width.

    a {
      display: inline-block;
      max-width: 100%;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
      text-decoration: none;
    }
    
    a:focus-within {
      box-shadow: 0 0 0 3px blue;
      text-decoration: underline;
    }
    
    a:focus-visible {
      outline: 0;
    }
    <a href="#">This is a long link that will be truncated. This is a long link that will be truncated. This is a long link that will be truncated.</a>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search