Search code examples
htmlcssanimationunderline

CSS Text underline animation issue


I'm trying to learn how to add an underline animation effect on my webpage, but am having a small issue.

Here's the code I used for the underline effect:

.cmn-t-underline {
position: relative;
}

.cmn-t-underline:after {
display: block;
position: absolute;
left: 0;
bottom: -10px;
width: 0;
height: 3px;
background-color: dimgrey;
content: "";
transition: width 0.3s;

}
.cmn-t-underline:hover {
color: #333;
}

.cmn-t-underline:hover:after {
width: 100%;
}

And here's the code on my css:

    <div class="col-sm-6">
    <h1 class="text-center text-padding cmn-t-underline">Access Everywhere</h1>
        <p class="text-center">Lorem ipsum dolor sit amet</p>
    </div>

And this is how it comes out once the animation is done:

enter image description here

My question is, how do I make it so that the underline only stays directly under the H1 header? I want the underline to start at 'A' and end at 'e', but I am having a hard time figuring out what to put in the code to fix this. I would really appreciate if someone can help me with this small issue.

Thanks in advance


Solution

  • You could use display-table on your h1 to simulate block like behaviour without the 100% width...

    body {
        text-align: center;
    }
    
    h1 {
        display: table;
        margin: 0 auto;
    }
    
    .cmn-t-underline {
        position: relative;
    }
    .cmn-t-underline:after {
        display: block;
        position: absolute;
        left: 0;
        bottom: -10px;
        width: 0;
        height: 3px;
        background-color: dimgrey;
        content:"";
        transition: width 0.3s;
    }
    .cmn-t-underline:hover {
        color: #333;
    }
    .cmn-t-underline:hover:after {
        width: 100%;
    }
    <div class="col-sm-6">
         <h1 class="text-center text-padding cmn-t-underline">Access Everywhere</h1>
         <p class="text-center">Lorem ipsum dolor sit amet</p>
    </div>