Home > Web Front-end > CSS Tutorial > How to Make nth-Child Selector Ignore Hidden Elements in a Grid Layout?

How to Make nth-Child Selector Ignore Hidden Elements in a Grid Layout?

DDD
Release: 2024-11-15 15:28:03
Original
400 people have browsed it

How to Make nth-Child Selector Ignore Hidden Elements in a Grid Layout?

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);
Copy after login

});

$('.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();
}
Copy after login

});

Explanation:

  • On page load, each item is given an initial index.
  • When the "Hide others" button is clicked:

    • If hidden divs exist, they are re-attached to the grid.
    • If no hidden divs exist, the elements with the class "css--all-photo" are detached from the grid, excluding them from the DOM and nth-child counting.

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template