← Back toCross browser

Conditional HTML classes based on user agent

Written byPhuoc Nguyen
Created
06 Sep, 2022
In the previous post, we use the conditional comment tags to add specific CSS classes to the root `html` element:
html
<!--[if lt IE 7]><html class="lt-ie7 lt-ie8 lt-ie9"><![endif]-->
<!--[if IE 7]><html class="lt-ie8 lt-ie9"><![endif]-->
<!--[if IE 8]><html class="lt-ie9"><![endif]-->
The conditional comments are ignored on other browsers except Internet Explorer (IE). The tag is also disabled from IE 10. How can we add additional classes for other browsers and older versions of IE?
We can detect a browser and its version based on the user agent. The following snippet checks if the current browser is IE 11 and adds corresponding CSS class if needed:
js
function detectIE11() {
if (navigator.userAgent.match(/Trident.*rv:11\./)) {
document.documentElement.classList.add('ie11');
}
}
As soon as the `ie11` class added to the root `html` element, you can add more styles explicitly for IE 11:
css
.ie11 .otherClass {
/* Styles for IE 11 */
}
The approach not only works with IE 11, but also can be used to support other browsers.
If you found this post helpful, please consider giving the repository a star on GitHub or sharing the post on your favorite social networks 😍. Your support would mean a lot to me!

Questions? 🙋

Do you have any questions about front-end development? If so, feel free to create a new issue on GitHub using the button below. I'm happy to help with any topic you'd like to learn more about, even beyond what's covered in this post.
While I have a long list of upcoming topics, I'm always eager to prioritize your questions and ideas for future content. Let's learn and grow together! Sharing knowledge is the best way to elevate ourselves 🥷.
Ask me questions

Recent posts ⚡

Newsletter 🔔

If you're into front-end technologies and you want to see more of the content I'm creating, then you might want to consider subscribing to my newsletter.
By subscribing, you'll be the first to know about new articles, products, and exclusive promotions.
Don't worry, I won't spam you. And if you ever change your mind, you can unsubscribe at any time.
Phước Nguyễn