Targeting first visible element with pure CSS

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.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)