← Back toCross Browser

Conditional HTML classes based on user agent

Written byPhuoc Nguyen
06 Sep, 2022
In the previous post, we use the conditional comment tags to add specific CSS classes to the root `html` element:
<!--[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:
function detectIE11() {
if (navigator.userAgent.match(/Trident.*rv:11\./)) {
As soon as the `ie11` class added to the root `html` element, you can add more styles explicitly for IE 11:
.ie11 .otherClass {
/* Styles for IE 11 */
The approach not only works with IE 11, but also can be used to support other browsers.

Questions? 🙋

Do you have any questions? Not just about this specific post, but about any topic in front-end development that you'd like to learn more about? If so, feel free to send me a message on Twitter or send me an email. You can find them at the bottom of this page.
I have a long list of upcoming posts, but your questions or ideas for the next one will be my top priority. Let's learn together! Sharing knowledge is the best way to grow 🥷.

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