Adding Hover Effects To Your Links Using CSS

Do you suffer from boring hover effects in your navigation bar? Look no further! Here are some CSS effects you can use to improve your website.

The method that we will be using for these effects is the pseudo class :after. Here is how it works:

Let’s start off with a basic navigation bar in your html.

<div class="example-nav">
    <a href="#">Link 1</a>
    <a href="#">Link 2</a>
    <a href="#">Link 3</a>
</div>

Next we will add some CSS to the navigation bar. It’s important that the position of the links are relative.

.example-nav {
    display: flex;
    flex-direction: row;
    justify-content: space-around;
}

/* This is important for the absolute positioning on the :after */
.example-nav a {
    position: relative;
}

Now we will add in the :after class to the links.

/* Expand from middle on hover */
.example-nav a:after {
    content: "";
    position: absolute;
    bottom: 0;
    left: 0;
    height: 2px;
    width: 0;
    margin: 50%;
    background-color: #000;
    -webkit-transition: all 0.3s ease;
    -moz-transition: all 0.3s ease;
    -o-transition: all 0.3s ease;
    -ms-transition: all 0.3s ease;
    transition: all 0.3s ease;
}

After we’ve added the :after content, we can add in the pseudo class for :hover and :focus.

.example-nav a:hover:after,
.example-nav a:focus:after {
    width: 100%;
    margin: 0;
}

This example will expand from the middle on hover. If you would like change it to expand from left or right; change the value of the starting margin.

/* Expand from left on hover */
.example-nav a:after {
    content: "";
    position: absolute;
    bottom: 0;
    left: 0;
    height: 2px;
    width: 0;
    margin: 0;
    background-color: #000;
    -webkit-transition: all 0.3s ease;
    -moz-transition: all 0.3s ease;
    -o-transition: all 0.3s ease;
    -ms-transition: all 0.3s ease;
    transition: all 0.3s ease;
}
/* Expand from right on hover */
.example-nav a:after {
    content: "";
    position: absolute;
    bottom: 0;
    left: 0;
    height: 2px;
    width: 0;
    margin: 100%;
    background-color: #000;
    -webkit-transition: all 0.3s ease;
    -moz-transition: all 0.3s ease;
    -o-transition: all 0.3s ease;
    -ms-transition: all 0.3s ease;
    transition: all 0.3s ease;
}
Recent Posts

Leave a Comment