Skip to content Skip to sidebar Skip to footer

What Are The Advantages Of Assigning Multiple Classes To An Html Element?

Why would an HTML element needed to be assigned multiple classes instead of a single class. I am referring to a code like this.

Solution 1:

Think of a scenario where you have a menu with font icons in each li element, each font icon shares common font-size, color and so on, so in that case we would write

<ul>
    <li><spanclass="icon fb">Something here</span></li><li><spanclass="icon twitter">Something here</span></li>
</ul>

.icon {
    font-size: 12px;
    color: black;
    display: inline-block;
    padding: 5px;
}

/* But content are unique so we define them separately */
.fb {
    content: "Facebook Icon";
}

.twitter {
    content: "Twitter Icon"
}

Here, it's essential for you to always define base properties i.e in .icon which has to be defined for every icon you set as each icon shares commonly. If you wanted to define a single class than you need to do something like this...

.fb,
.twitter {
    content: "Facebook Icon";
    font-size: 12px;
    color: black;
    display: inline-block;
    padding: 5px;
}

/* Need to override because previous declaration was set for facebook */.twitter {
    content: "Twitter Icon";
}

As you see, overrides started coming in, so it depends on what you are trying to do, sometimes things are easily achievable with a single class but sometimes declaring multiple classes on a single element makes more sense, you can also take a look at CSS Grids which usually follow multiple class declaring patterns.

The case I shared is limited to a navigation bar, I usually create self clearing classes like

.clear:after {
    content: "";
    display: table;
    clear: both;
}

Now I call this class on every element where the child elements are floated

<navclass="navbar clear"><divclass="floatedtoleft"></div><divclass="floatedtoright"></div></nav>

It makes much more sense to declare a common class instead of doing something like

Gets simple here with that single declaration instead of you specifying clearance for each and every element in your stylesheet

/* Bad Practice */.elm1_holds_child_floats:after,
.someotherelm_child_floats:after,
nav:after,
section.some_otherelm:after {
    /* Clear floats for above elements here and this is shitty */
}

I hope this clears your doubt that why you need to use multiple classes in some cases, you don't need to declare multiple classes every time, it depends on you that how well you write your CSS and how tight you want it to be.

Post a Comment for "What Are The Advantages Of Assigning Multiple Classes To An Html Element?"