Rajat Gupta
Rajat's Blog

Rajat's Blog

How to make a badge component in CSS (using transform: translate())

Rajat Gupta's photo
Rajat Gupta
·Feb 7, 2022·

2 min read

Subscribe to my newsletter and never miss my upcoming articles

Since you are here, probably you already know what a badge is, but anyway let me explain it first. 0.PNG Badges are used to highlight an item's status for quick recognition. There are many use cases of the badge:

  1. you must have seen that when we have something unread on WhatsApp, Twitter, Quora, etc. a badge icon with a number appears on the top right of the app to let us know how many messages are unread.
  2. or to show how many items are there in our cart of an e-commerce website.

There are many ways using which we can make a badge. Here we'll see how easy it is to make the badge component using the translate function of the transform property. If you don't know what it is, read my blog here.

so, let's get to the code because as the saying goes "talk is cheap, show me the code".

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        p{
            background-color: red;
            height: 22px;
            width: 22px;
            display: flex;    /* to center the content inside red circle */
            border-radius: 99rem;
            justify-content: center;
            align-content: center;
            transform: translate(-100%, -90%);    /* only thing we need */
        }
    </style>
</head>

<body>
    <img src="notification.svg">
    <p>2</p>
</body>
</html>

1.PNG 2.PNG 3.PNG

You can see ☝️ how seamlessly we moved the red circle around the icons using the transform property.

That's all folks.

I write one article every day related to web development (yes, every single f*cking day). Follow me here if you are learning the same.

my Twitter handle: @therajatg

If you are the Linkedin type, let's connect: linkedin.com/in/therajatg

Have an awesome day ahead 😀!

 
Share this