CSS border (‘:after’) not expanding full width when the text is wrapped

I am trying to add and animate a line under a link using CCS but the positioning of the line (or, perhaps, its width) breaks when the text wraps.

Here is an illustration of what I am trying to achieve and what the problem is:

  • normal behavior:

    enter image description here

  • breaking:

    enter image description here

Here is the fiddle of the illustration: https://jsfiddle.net/b1zajhs5/. To make it break, just shrink the result panel until the text wraps.

This is the HTML used

<div class="centered">
  <a href="#"><span class="effect-underline">Some Text That Has to Be Quite Long To Prove the Point</span></a>
</div>

And this is the SCSS:

.centered {
  border: 1px solid #ccc;
  width: 80%;
  margin: 2rem auto;
  padding: 1.5rem .5rem;
  text-align:center;
}


a {
  text-decoration: none;
}


.effect-underline {
    position: relative;

  &:after {
        content: '';
        border-bottom: 1px solid;
        width: 100%;
        height: 1em;
        display: inline-block;
        margin-top: 10px;
        position: absolute;
        left: 0;
        opacity: 0;
        transition: all 0.35s;
        transform: scale(0, 1);
    }

    &:hover {
        &:after {
            opacity: 1;
            transform: scale(1);
        }
    }
}

Do you know how the line can be expanded the match the full width of the link when the text is wrapped?

2 thoughts on “CSS border (‘:after’) not expanding full width when the text is wrapped”

  1. Add display: inline-block; to .effect-underline to make it go across when the text wraps.

    .centered {
    border: 1px solid #ccc;
    width: 80%;
    margin: 2rem auto;
    padding: 1.5rem 0.5rem;
    text-align: center;
    }

    a {
    text-decoration: none;
    }

    .effect-underline {
    display: inline-block;
    position: relative;
    }
    .effect-underline:after {
    content: "";
    border-bottom: 1px solid;
    width: 100%;
    height: 1em;
    display: inline-block;
    margin-top: 10px;
    position: absolute;
    left: 0;
    opacity: 0;
    -webkit-transition: all 0.35s;
    transition: all 0.35s;
    -webkit-transform: scale(0, 1);
    transform: scale(0, 1);
    }
    .effect-underline:hover:after {
    opacity: 1;
    -webkit-transform: scale(1);
    transform: scale(1);
    }

    <div class="centered">
    <a href="#"><span class="effect-underline">Some Text That Has to Be Quite Long To Prove the Point</span></a>
    </div>

  2. The reason why display: inline-block worked, was because a span, by default has a inline display. So, naturally, the line is going till the end of a text, and the end was on last sentence, that broke bellow.
    giving it a display of inline-block, an element becomes like a block element, so the line goes till the end of a block, not the end of a sentence.

Leave a Reply

Your email address will not be published.