CSS selector: how to select non-element sibling no

2019-04-22 04:45发布

问题:

According to the specification here: http://www.w3.org/TR/CSS21/selector.html#adjacent-selectors

Adjacent sibling selectors have the following syntax: E1 + E2, where E2 is the subject of the selector. The selector matches if E1 and E2 share the same parent in the document tree and E1 immediately precedes E2, ignoring non-element nodes (such as text nodes and comments).

So how can we select the non-element sibling node. For example: in the following html, how can we select the "Non-element text" text?

<div><label>Some text here</label> Non-element text</div>

回答1:

You can't. CSS selectors can only select element nodes. This is why the adjacent sibling combinator works as described.

If you need to apply styles, try applying them to the div and overriding them in the label. This does depend on what styles you're applying, of course, since some of the styles can't be undone or are subject to inheritance.



回答2:

As stated before, CSS selectors can only select element nodes.

To solve your problem, you can either wrap the text node in an element, and apply styles on this element, or apply the style on the container element, and override it in the label element.