Explain Codes LogoExplain Codes Logo

How to assign multiple classes to an HTML container?

html
responsive-design
css
javascript
Anton ShumikhinbyAnton Shumikhin·Sep 24, 2024
TLDR

To assign multiple classes to an HTML element, use space-separated values:

<article class="class1 class2 class3"></div> <!-- Three amigos dancing together -->

All assigned classes contribute to the element's appearance, providing distinct styles defined in the CSS.

Class Order in CSS and HTML

Although the class order in HTML doesn't directly affect the element's style, the sequence in the CSS does:

.primary { color: blue; } .secondary { color: red; }
<div class="primary secondary">This text would be red!</div> <!-- Not so innocent blue -->

Here, understand how cascade in Cascading Style Sheets (CSS) works, not leaving it to Lady Luck!

Global and Component Style Fusion

On a mission to create aesthetically pleasing elements, global utilities and component specific styles join forces:

<div class="padding-10 border rounded user-profile-card"></div>

This is smart styling at three levels - reusable utilities, border styles, and component-specific styles.

Dynamic Wittiness with Classes

When JavaScript — the good cop — enters with frameworks like Vue.js or jQuery, classes can be played around with:

// jQuery example $('div').addClass('sunshine'); // Adding some sunshine to the div! // Vue.js example <div :class="{ ownTheNight: isNight }"></div> // Become the night owl!

This makes the webpage lively, changing styles based on user interactions like a chameleon changes color.

Crafted for Responsiveness and States

Multiple classes become knights in shiny armor when it comes to responsive and state-driven styles:

<div class="text-sm md:text-lg hover:bg-purple-500 focus:border-blue-500"></div>

This domain is ruled by varied text sizes across devices and stylish borders appearing upon focus or hover. Responsiveness and user engagement are the keys to the kingdom!

Pitfalls to Circumnavigate

No space travel here, simply space-separated classes. Commas or dots may lead to the Bermuda Triangle of classes:

<div class="class1,class2"></div> <!-- Hello Bermuda Triangle! -->

Correct way:

<div class="class1 class2"></div> <!-- Voila! 👌-->

And, remember the weird world of CSS: no numbers or special characters at the start of class names!