Why does putting comma selectors inside a space selector break the parent?

夙愿已清 提交于 2020-01-04 07:04:22

问题


I am used to using descendant space selectors and comma selectors. I have ids around larger sets of elements in order to manipulate them easier in jquery and css.

So I tried something like this:

#parent_id input, textarea
{
 width: 100px;
}

So when I do this, my expectation is that this effect will occur on input AND textarea inside the #parent_id. Instead, this disqualifies parent_id and just selects all input, textarea. Why? And how can I avoid this, aside from making them separate.


回答1:


In CSS, rules have the form:

selector0 [, selectorN ]*
{
    property0: value0[,
    property1: value1]*
}

So the comma , is used to separate different selectors for the same property set. For example, if you wanted two radically different selectors for the same property set.

Selectors in CSS must be fully-qualified, there is no contextual-sensitivity - this is partly because CSS is designed to be forward-compatible: browsers are instructed to try each and every selector in a rule independently, so browsers gracefully-degrade when they encounter new selector syntax they don't support.

To get the effect you want just type more :)

#parent_id input,
#parent_id textarea {
    width: 100px;
}

Note that there is a proposed/experimental :matches() selector function which works as a logical OR operator in selectors, it's in the CSS Level 4 Selectors specification (currently in a working-draft state, as of 2016-05-04: https://drafts.csswg.org/selectors-4/ ).

The matches-any pseudo-class, :matches(), is a functional pseudo-class taking a selector list as its argument. It represents an element that is represented by its argument.

So in your case it would be:

#parent_id :matches( input, textarea ) {
    width: 100px;
}

But I don't think this usage is really that better, it's less obvious and requires greater knowledge of CSS.



来源:https://stackoverflow.com/questions/37038553/why-does-putting-comma-selectors-inside-a-space-selector-break-the-parent

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!