Creating a Notification Badge with HTML5 and CSS3

I recently wanted to add a notification badge to a website. I wasn't sure what the best approach was, but I knew I didn't want to add extra markup and position it with CSS. I also didn't want to use a jQuery plugin to add this little feature.

I ultimately decided to use the HTML5 data- attribute with the CSS attr() function. It works in most browsers including IE 8+ which was good enough for me because it wasn't a required feature on the site.

The HTML

<ol>
  <li>
    <a data-notifications="10" class="button" href="#">New Comments on Your Posts</a>
  </li>
  <li>
    <a class="button" href="#">Number of Post Likes :)</a>
  </li>
<ol>

All the magic is in the data-notifications attribute. It's really easy to add to any element and can be easily grabbed with CSS.

The CSS

/* make sure the element has position: relative */
[data-notifications] {
  position: relative;
}

/* append the notification badge after it */
[data-notifications]:after {

  /* the burger */
  content: attr(data-notifications);

  /* the fries */
  position: absolute;
  background: red;
  border-radius: 50%;
  display: inline-block;
  padding: 0.3em;
  color: #f2f2f2;
  right: -15px;
  top: -15px;   
}

This is a great example of why I love the simplicity of CSS. The seemingly complex idea of appending the data-notifications value is actually really simple. Most of the CSS is just making it look good.

The Demo

Check out this Pen!

  • Dhamir

    very good work ^^
    but how can you increment the data-notifications’s value, per example when you clik button the value ++ ??

    • http://baylorrae.com Baylor Rae’

      This would need to be done with javascript. I’ve created a simple demo for you to look at. http://jsfiddle.net/GgyJ5/1/

  • Jamie Lee Perkins Dalton

    Excellent and worked perfectly for my shopping cart. Thanks.

  • hbensalem

    thank you very useful !

%d bloggers like this: