Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a simple CSS badge system [closed]

Tags:

css

badge

I need a simple badge system that can be applied to numerous types of html elements.

Something like the ones you find on a messaging app on your mobile phone.

Something like this;

enter image description here

like image 630
Mokky Miah Avatar asked Dec 24 '22 14:12

Mokky Miah


1 Answers

Answering my own question for the benefit of others.

Recently I have created a badge system using css that can be applied to any html element.

I hope this helps anyone else that is looking for something like this.

This is done using css pseudo element being applied after the host element. A badge can be applied to any element by simply adding a badge attribute with a value.

Some host elements may need to add overrides if the badge's default position/style is not suitable.

The content of the pseudo element is inherited from the attribute badge.

If no value, a value of 0 or a negative value is given, the badge will not display by default. If you need to display badge with 0 or a negative value, use css override or remove the rules from your css file.

Example of an override;

.my-unusual-element[badge="0"]:after {
    display: initial;
}

This is a CSS only solution and is intended to be a light weight badge system.

I posted a fiddle here for demo.

[badge]:after {
      background: red;
    border-radius: 30px;
    color: #fff;
    content: attr(badge);
    font-size: 11px;
    margin-top: -10px;
    min-width: 20px;
    padding: 2px;
    position: absolute;
    text-align: center;
}

[badge^="-"]:after,
[badge="0"]:after,
[badge=""]:after {
   display: none;
}
<span badge="">Empty string</span>
<br>
<br>
<span badge="-1">-1</span>
<br>
<br>
<span badge="0">0</span>
<br>
<br>
<span badge="1">1</span>
like image 198
Mokky Miah Avatar answered Jan 15 '23 05:01

Mokky Miah