Home > Web Front-end > CSS Tutorial > How to Style Rows Correctly with nth-child Selectors When Hidden Elements Exist?

How to Style Rows Correctly with nth-child Selectors When Hidden Elements Exist?

DDD
Release: 2024-11-29 02:18:08
Original
181 people have browsed it

How to Style Rows Correctly with nth-child Selectors When Hidden Elements Exist?

How to Bypass Hidden Elements When Using nth-child Selectors

The nth-child selector allows you to target elements based on their position among their sibling elements. However, this selector counts hidden elements, which can cause problems when you want specific rows in a grid to display differently.

In your case, you're using nth-child selectors to change the appearance of every nth row in a grid of blocks. When you hide some blocks using display: none, the nth-child selector still counts them, leading to incorrect styling.

CSS-Based Solution

Unfortunately, there's no pure CSS solution to this problem. The nth-child selector simply looks at all siblings, regardless of their visibility.

jQuery-Based Solution

To avoid including hidden elements in your nth-child calculations, you need to remove them from the DOM when they're hidden. jQuery provides a .detach() method for this purpose:

$(".hide-others").click(function () {
  var divs;

  $(".photos-board-item").each(function (i) {
    $(this).data("initial-index", i);
  });

  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

This code removes the hidden elements from the DOM when the "Hide others" button is clicked. When the button is clicked again, the elements are reinserted into the DOM, preserving their original order.

Demo

Here's a demo that demonstrates the solution:

[DEMO FIDDLE]

By using the .detach() method, you can toggle the visibility of elements without breaking the nth-child selector logic, ensuring that every row in your grid maintains its desired appearance.

The above is the detailed content of How to Style Rows Correctly with nth-child Selectors When Hidden Elements Exist?. 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 Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template