Can I make this CSS simpler to avoid repeating the parent selector?
A common pattern I come across is the following:
form.request input {
/* ... */
}
form.request input[type="text"] {
/* ... */
}
form.request select {
/* ... */
}
form.request br {
/* ... */
}
I have several lines beginning with the same selector (form.request
), and I want to select various children. Can I do this in a neater way without the repetition (and preferably without additional dependencies like LESS)?
Related question - if 开发者_运维知识库all the above comments contain the same styles, can I do better than:
form.request input, form.request input[type="text"], form.request select, form.request br {
/* ... */
}
No, you cannot. But if you want to do less typing and make the stylesheets more readable, consider using SCSS.
Use LESS, which would let you write
form.request {
input { /* ... */ }
input[type="text"] { /* ... */ }
select { /* ... */ }
br { /* ... */ }
}
or even
form.request {
input {
/* ... */
&[type="text"] { /* ... */ }
}
select { /* ... */ }
br { /* ... */ }
}
Not yet - or not without additional dependencies.
There is in fact a W3C working draft for a CSS Nesting Module - however, no browser supports this yet.
If you're willing to use PostCSS, there is a plugin available, so you can start using this feature now - the plugin will expand nested selectors (similarly to SASS or LESS) into repeated selectors that work in browsers today.
PostCSS enables many other CSS features to work in older browsers. The risk of using future CSS features, is that they may end up being different in their final form - or, for that matter, might never be implemented. On the other hand, using an evolving standard, if it is eventually implemented by browsers, you are most likely closer to something resembling the feature in it's final form than you would be with e.g. SASS or LESS.
Note that the syntax is similar but different from that of SASS or LESS.
You also might want to consider the issue of IDE support. For instance, there is a VS Code plugin available, and it does support the CSS Nesting Module in it's current form - however, depending on your IDE of choice, a PostCSS plugin may or may not be available, and may or may not support certain features.
精彩评论