Using multiple vendor-specific CSS selectors at on

2019-08-16 02:18发布

I'm styling placeholder text, and need to use several vendor-prefixed selectors so that it works in different browsers. When I put each of them as a separate code block, it works. However, if I use a comma-separated list of selectors instead of repeating the same CSS for each of them, it won't work. Can anyone explain?

This works:

input[type=text]::-webkit-input-placeholder {
    color: green;
}
input[type=text]::-moz-placeholder {
    color: green;
}
input[type=text]:-ms-input-placeholder {
    color: green;
}
input[type=text]:-moz-placeholder {
   color: green;
}
<input type="text" placeholder="Placeholder Text" />

But this doesn't:

input[type=text]::-webkit-input-placeholder,
input[type=text]::-moz-placeholder,
input[type=text]:-ms-input-placeholder, 
input[type=text]:-moz-placeholder {
	    color: green;
}
<input type="text" placeholder="Placeholder Text" />

Why?

2条回答
Emotional °昔
2楼-- · 2019-08-16 03:00

The reason why you can't group these selectors is because as soon as a browser comes across an unknown selector it stops execution for that block of code.

Vendor-specific selectors are only known to the browser that supports them. If you group them, every browser will stop executing that block of code either at the first selector in the group or at the second.

In this example:

input[type=text]::-webkit-input-placeholder,  /* Chrome / Opera / Safari */
input[type=text]::-moz-placeholder,           /* Firefox 19+ */
input[type=text]:-ms-input-placeholder,       /* Edge/IE 10+ */
input[type=text]:-moz-placeholder {           /* Firefox 18- */
    color: green;
}

Google Chrome, Safari, and Opera will recognize the first selector, but they will stop executing this block of code at the second selector, which is only valid in a Firefox browser. The other browsers will stop execution at the very first selector.

Therefore each of these selectors must have their own block of code.

查看更多
叛逆
3楼-- · 2019-08-16 03:04

Unfortunately, you can't.

When a selector that the browser does recognise as valid is found, it stops execution of the code block following it.

Only one of the vendor-prefixed selectors you are using will exist in each browsers (for example WebKit browsers do not have the Mozilla and Microsoft vendor-prefixed selectors); therefore you will never be able to execute that block as there is no browser where all three pseudo-selectors are valid.

However...

... you can simply use three different blocks. For example, this should work:

input[type=text]:focus::-webkit-input-placeholder {
  color: green;
}

input[type=text]:focus::-ms-input-placeholder {
  color: green;
}

input[type=text]:focus::-moz-placeholder {
    color: green;
}
<input type="text" placeholder="Hello, world!">

If you have a lot of code, you could use a preprocessor like LESS or SASS to dynamically put the same code inside each block.

查看更多
登录 后发表回答