Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Targeting first visible element with pure CSS

Tags:

jquery

css

I am wondering if it is possible to transpose the following into pure CSS.

$('.child:visible:first').css({'border-top':'1px solid #cccccc','border-bottom':'1px solid #cccccc'}); 

I cannot seem to find a solution.

like image 590
Paul Avatar asked Sep 12 '13 13:09

Paul


People also ask

How do you select the first section in CSS?

The :first-of-type selector in CSS allows you to target the first occurence of an element within its container. It is defined in the CSS Selectors Level 3 spec as a “structural pseudo-class”, meaning it is used to style content based on its relationship with parent and sibling content.

Is CSS a visible selector?

Because :visible is a jQuery extension and not part of the CSS specification, queries using :visible cannot take advantage of the performance boost provided by the native DOM querySelectorAll() method.

How do you target every other element in CSS?

The :nth-child(odd) property will target every other item of the element you have selected.


1 Answers

As an abstract, it's not possible: jQuery relies on traversing the DOM to programatically determine an element which fits various conditions, then stops. You can't do this. But I assume in practice you will know various things. This solution assumes:

  1. You know how these .child elements are going to be hidden. Will they have display: none as an inline style (if you've used jQuery .hide() on them, they will)? Do they have a class of .hidden? As long as you know the method, there will be a selector you can use to represent this. You can use this in combination with the CSS3 :not() selector.
  2. Since these are called .child, I'm assuming they're all siblings — none are nested inside other .child elements, and they all share the same parent.

If either of the above isn't true, it's impossible. But if they're both true:

.child:not( [style*='display: none'] ) {     border-top:    1px solid #cccccc;     border-bottom: 1px solid #cccccc; }  .child:not( [style*='display: none'] ) ~ .child:not( [style*='display: none'] ) {     /* ...or whatever the default styles are */     border-top:    none;     border-bottom: none; } 

The :not() pseudo-class is fairly obvious: it only selects elements which don't match the contained selector. The ~ operator means that the selector to the right will be the target if it is a sibling of the selector on the left appearing afterwards in the source code.

like image 134
Barney Avatar answered Sep 23 '22 17:09

Barney