Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS no sibling selector

Consider the following html:

<div>     <div class="iwant" />     <div class="idontwant" /> </div>  <div>     <div class="iwant" /> </div> 

I'm interested in a selector (for crawling content so I can't modify html) that would select all iwant that DO NOT have sibling with class idontwant.

like image 228
Chris Hasiński Avatar asked Oct 23 '11 14:10

Chris Hasiński


People also ask

How do you target a sibling in CSS?

Adjacent Sibling Selector (+) The adjacent sibling selector is used to select an element that is directly after another specific element. Sibling elements must have the same parent element, and "adjacent" means "immediately following".

Does CSS have previous sibling selectors?

No, there is no "previous sibling" selector. On a related note, ~ is for general successor sibling (meaning the element comes after this one, but not necessarily immediately after) and is a CSS3 selector. + is for next sibling and is CSS2.

How do I select a second sibling in CSS?

You use the general sibling selector (~) in combination with :hover . The ~ combinator separates two selectors and matches the second element only if it is preceded by the first, and both share a common parent.


2 Answers

There is no sibling selector to match elements (or not) by class.

The closest selector I can think of is

.iwant:only-child 

But this selector means that there cannot be any other elements besides that div class="iwant" as children of the parent div, regardless of type or class. This may fulfill your need depending on the structure of your HTML though, so it's worth a try. If class names are a problem for you, though, then there probably isn't much of a solution, because there isn't an :only-of-class pseudo-class in CSS which filters by class and ignores the rest.

like image 127
BoltClock Avatar answered Sep 21 '22 08:09

BoltClock


There's no good way to target an item without a specific sibling item. But you can use .iwant:last-child to target items that doesn't have a subsequent sibling.

Example: http://codepen.io/martinkrulltott/pen/YyGgde

like image 34
Martin Avatar answered Sep 21 '22 08:09

Martin