Rafa Llorente
Rafa Llorente

Reputation: 447

NOT first element with a given class

I have some code like this:

<span class="item multifilter-wrapper multifilter">
  <span class="item multifilter multifilter-item">
    <div></div>
  </span>
  <span class="item multifilter multifilter-item">
     <div></div>
  </span>
  <span class="item multifilter multifilter-item hasdata">
     <div>HELLO</div>
  </span>
</span>

Any multifilter-item span could have content, if it has content I add the hasdata class, as in the last item.

I would like to add a separator in between 2 multifilter-item spans in case there is more than one with data, so I have this BEFORE rule:

.multifilter-wrapper .hasdata:not(:first-child)::before{
   content: '|';
}

However it is adding the content in the example above with just 1 hasdata span.

Any ideas why?

Upvotes: 0

Views: 70

Answers (2)

Luca
Luca

Reputation: 9745

without having to modify your markup, you can use the general sibling selector: ~ (http://www.w3.org/TR/css3-selectors/)

http://jsfiddle.net/ossx1v1k/

.multifilter-wrapper .hasdata ~ .hasdata::before{
   content: '|';
}

please note that I've removed the div tags from inside the span tags in my jsfiddle example, because as Paulie_D remarked, it's invalid markup to have block elements inside inline ones.

Upvotes: 1

musefan
musefan

Reputation: 48455

This is because .has-data is not the the first child, so it matches as expected.

I think you are confused as to what :first-child does. It checks if it is the first child element for it's parent (which it is not as you have 2 other ones before it). It does not check if it's the first child that is also a .hasdata class.

Basically the logic is:

  • class is hasdata
  • AND is not the first child element

To which it matches these rules, which is why the content separator is added.

There is no way to identify classes that are the first child with a specific class name in only CSS, you cannot write a rule for "is not the first hasdata class". I suggest you modify the html to have something like notfirsthasdata to identify elements that are not the first ones with content.

There is first-of-type which is the type of logic you want, however I believe this only matches with the element type (in your case span) and not the class name.

Upvotes: 1

Related Questions