How to make cool buttons with CSS

Cool CSS buttons

Hey there, always wondered how to make cool CSS buttons with beautiful animations? well, I have got just the tutorial for you.

Most animated CSS buttons are made using pseudo-elements (::before and ::after).
The ::before pseudo-element can be used to insert some content before the content of an element. The ::after pseudo-element can be used to insert some content after the content of an element.


Let's start by making this simple animation using pseudo-elements
In this example, we can simply design the button how we normally would and add the pseudo-element for the hover state to give that cool animation.

We'll start with the basic HTML:
  		<button class="btn">Hover</button>

 Now add the basic css for the button:	
 	.btn{
            color: #4895ef;
            font-size: 1rem;
    	    cursor: pointer;
            transition: 0.2s;
            position: relative;
            overflow: hidden;
            padding: 0.8rem 1.2rem;
            border: 1px solid #4895ef;
        }

Output:    
At this stage, we have a simple button that has no animation on mouse hover, now let us start by making the pseudo-element to add the hover animation.  Since we need an element before the contents of the button we will use the ::before pseudo-element


CSS for the pseudo-element: 
    	.btn::before{
            content: '';
            position: absolute;
            height: 100%; //to inherit height and width of the button
            width: 100%;
            margin: -0.8rem calc(-100% - 1.2rem);  //this is to remove it out of screen
            z-index: -1;
            transition: 0.5s;
            background: #4895ef;
        }
    
Now we have the pseudo-element ready, all we have to do is remove the margins that remove it out of the screen when the user hovers over the button.

    .btn:hover::before{
        margin: -0.8rem -1.2rem;
    }
Also, we need the font color of the button to be changed on hover, otherwise, it would match with the background and won't be visible.

    .btn:hover{
        color: #fff;
    }

And ta-da, we have a cool animated button made with just CSS. 
You can use this technique to create all sorts of animated buttons. Have fun!

~Arvind Suthar

Comments

Popular posts from this blog

How to code neural networks (Part 1)