1

I had a situation where I had to apply a specific CSS style in Edge and IE browsers only. I found online that you can prepend your CSS selector with _:-ms-lang(x) and the style will only be applied in IE and Edge.

But I wonder, how exactly is this fix working? As far as I know, the comma will just separate different selectors, meaning that other browsers should also interpret and use this style.

Here is an example:

Let's say we want to apply a width of 94px to .selector element only in Edge and IE.

_:-ms-lang(x), .selector { 
    width: 94px;
}

The Edge browser will apply this style, and others won't. But why not?

The comma in the selector should apply the style to _:-ms-lang(x) element AND to .selector element.

Here is a source for this IE hack.

And one more.

TylerH
  • 20,799
  • 66
  • 75
  • 101
papa zulu
  • 317
  • 5
  • 16
  • 2
    if a browser don't know one of the selector, all will get ignored even using comma (the purpose of the hack) – Temani Afif Dec 25 '18 at 20:14
  • I don't know how this works, but it reads as a CSS hack; as for your comment "*But I was wondering, how exactly is this fix working? As far as I know, the comma will just separate different selectors, meaning that other browsers should also interpret and use this style.*" - no, unexpectedly (to me), if a browser doesn't understand a selector (which makes it invalid) it must discard the entirety of that selector including those that are comma-separated: "*a group of selectors containing an invalid selector is invalid*" ([reference](https://www.w3.org/TR/selectors-3/#Conformance)). – David Thomas Dec 25 '18 at 20:14
  • 1
    Hey guys, why don't you post that as an answer, since that's what the OP wants to know. – Mr Lister Dec 25 '18 at 22:01

1 Answers1

2

In CSS, when a browser does not recognize part of a selector (or thinks there is an error in a selector), it completely ignores the entire rule.

Here's the section in the CSS3 spec outlining this behavior

The prelude of the qualified rule is parsed as a selector list. If this results in an invalid selector list, the entire style rule is invalid.

Here CSS2.1 talks about the special case of comma

CSS 2.1 gives a special meaning to the comma (,) in selectors. However, since it is not known if the comma may acquire other meanings in future updates of CSS, the whole statement should be ignored if there is an error anywhere in the selector, even though the rest of the selector may look reasonable in CSS 2.1.

Therefore when the other browsers try to parse the selectors, they find the _:-ms-lang(x) selector to be invalid and so ignore the entire rule (including .selector)

Also here is an excellent answer on why this behavior is desirable

Burhan
  • 668
  • 5
  • 27
  • What I wondering is how does this work in IE, is it a valid selector that just doesn't apply to anything? – Olga Aug 16 '19 at 17:39