Targeting first visible element with pure CSS

It is posible if you know how it is implemented the hiding. For instance, this would select the first visible element after a block (+1) of hidden elements:

li[style*="display:none"] + li:not([style*="display:none"]) {
  /* ... */
  background-color: blue;
  color: white;
}
<ul>
  <li style="display:none">hidden</li>
  <li style="display:none">hidden</li>
  <li>visible, selected</li>
  <li>visible, not-selected</li>
  <li style="display:none">hidden</li>
  <li>visible, selected</li>
  <li>visible, not-selected</li>
</ul>

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.

Tags:

Css

Jquery