Skipping Hidden DIVs in nth-Child Selector
Problem:
When using the nth-child selector to style elements in a grid layout, hidden elements are still counted as siblings, disrupting the desired styling.
Pure CSS Solution (Not Possible):
The nth-child selector considers all siblings regardless of their visibility, so it's not possible to ignore hidden elements using only CSS.
jQuery Solution:
To solve this issue, we can use jQuery to remove hidden elements from the DOM, effectively "excluding" them from the nth-child selector's count. Here's the modified code:
<br>var divs;</p> <p>$('.photos-board-item').each(function(i){</p> <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">$(this).data('initial-index', i);
});
$('.hide-others').on('click', function () {
if(divs) { $(divs).appendTo('.row').each(function(){ var oldIndex = $(this).data('initial-index'); $('.photos-board-item').eq(oldIndex).before(this); }); divs = null; } else { divs = $('.css--all-photo').detach(); }
});
Explanation:
When the "Hide others" button is clicked:
Using this jQuery-based approach, the nth-child selector only counts visible siblings, ensuring the desired grid styling regardless of which or how many divs are hidden.
The above is the detailed content of How to Make nth-Child Selector Ignore Hidden Elements in a Grid Layout?. For more information, please follow other related articles on the PHP Chinese website!