Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combine :not() and :first-child() selectors [duplicate]

I'm looking for a way to combine two css selectors. In my case, ':not' and ':first-of-type'. This is my code:

<div id="holder">
  <div class="image mobileOnly">...</div>
  <div class="image">...</div>
  <div class="image">...</div>
  <div class="image">...</div>
  <!-- ... more images ... -->
</div>

I'd like to select the first div.image that's doesn't contain the 'mobileOnly' class.

I tried the following combinations (in different orders):

#holder .image:not(.mobileOnly):first-of-type {
  border: 5px solid #0a85d4;
}

#holder .image:not(.mobileOnly) :first-of-type {
  border: 5px solid #0a85d4;
}

Is this possible at all?

like image 664
sanderbee Avatar asked Dec 21 '15 10:12

sanderbee


People also ask

Can Universal selectors be used in combination with other selectors?

Universal CSS Selector The three lines of code inside the curly braces ( color , font-size , and line-height ) will apply to all elements on the HTML page. As seen here, the universal selector is declared using an asterisk. You can also use the universal selector in combination with other selectors.

What is the difference between '+' and '~' sibling selectors?

+ will only select the first element that is immediately preceded by the former selector. ~ selector all the sibling preceded by the former selector.


2 Answers

This is a tricky question : I don't think there's a simple way to achieve that :)

As far as I understand : you try to select the first .image element, as long as it's not a .mobileOnly element ?

#holder .image:first-child {
  border: 5px solid #0a85d4;
}
#holder .image.mobileOnly:first-child {
  border: none;
}
#holder .image.mobileOnly:first-child + .image {
  border: 5px solid #0a85d4;
}

Live example : http://codepen.io/enguerranws/pen/wMWzBr

Let's explain this : you were trying to select the first child of type .image, which as class .onlyMobile > this couldn't work, because in the case you need, .image wasn't the first child of its type.

like image 147
enguerranws Avatar answered Oct 25 '22 17:10

enguerranws


If you want to select the first image which doesn't have the mobileOnly class then I would go about it like this:

Set the border on all the images which don't have the the mobileOnly class.

 #holder .image:not(.mobileOnly) {
      border: 5px solid #0a85d4;
 }

Now, at this stage there are still images - after that first one which we are after - that still have the border, so....remove them!

#holder .image:not(.mobileOnly) ~ .image {
  border: none;
}

Codepen Demo

The advantage of this approach is that it will work even if the first multiple elements have the mobileOnly class - it will still style the first image without the mobileOnly class. (demo)

like image 26
Danield Avatar answered Oct 25 '22 18:10

Danield