Zebra lines overlooking unseen details

Imagine having a table where rows can be dynamically assigned classes such as .hidden, which hide those rows using CSS. The rows are styled with alternating colors, like this:

tr:nth-child(even) {
    background-color: $light-grey;
}

But here's the catch - I want every even row that is not hidden to still have shading. This means hidden rows should not be included when applying the :nth-child(even) rule in order to maintain a consistent pattern. I tried the following code but it didn't achieve the desired result.

tr:not(.hidden):nth-child(even) {
    background-color: $light-grey;
}

The issue is that :nth-child() refers to the original row indices, rather than considering the selection scope specified by tr:not(.hidden). It's like the two rules are stacked on top of each other without interacting properly.

Is there a concept similar to :nth-of-scope/selection() (or maybe just :nth()) in CSS? Are there any alternatives or workarounds available?

Or do I need to turn to Javascript for help?

(Just to clarify, I also have the option of using jQuery)

Answer №1

If you're looking to hide elements in the DOM using CSS, simply adding properties like display:none or visibility:hidden won't do the trick.

Instead, you'll need a bit of JavaScript to achieve this effect after the page has loaded. Check out an example here:

var trs = document.getElementsByTagName("tr"), // Choose the specific ones you want
    count = 0; // Counter for visible elements

for(var i = 0; i < trs.length; i++) {    
    if(!trs[i].classList.contains("hidden") && (count++)%2 == 0) { // Apply style to odd elements
        trs[i].style.background = "black";
    } else if(!trs[i].classList.contains("hidden")) { // Apply style to even elements
        trs[i].style.background = "lightgrey";
    }
}

Answer №2

Discovering the simplicity of jQuery compared to CSS hacking:

rows = $('table tbody tr');
rows.find('tr:visible:odd').css('background-color', '#f7f7f7');

Including styles for both even and odd rows:

rows.find('tr:visible').each(function(i) {
    if (i%2) {
        $(this).css('background', '#f7f7f7');
    } else {
        $(this).css('background', 'none');
    };
});

I admit, I answered my own question—should have mentioned my use of jQuery!

Hoping that :visible and :even become part of the official CSS standard soon.

Answer №3

To resolve the issue, I successfully found a solution by inserting an additional <tr> element with the CSS property display: none; applied. This approach worked effectively in situations where a group of hidden rows contained an odd number of elements. While it may not be ideal for all scenarios, it proved to be a reliable method especially when constructing expanding tables using multiple rows.

Answer №4

It seems that achieving this purely with CSS might be a challenge. Even when using display:none; and visibility:hidden;, the table background color appears to be affected because the items still exist in the DOM. You could consider utilizing JQuery's remove() function for a cleaner solution. For a demonstration, check out my straightforward example on this jsfiddle link.

Answer №5

A clever solution using only CSS (no JavaScript) is as follows:

To achieve the desired effect, hide a row using a different tag instead of a class. In this example, the "ul/li" tags are replaced with the "del" tag for hiding purposes.

.list div:nth-of-type(odd) { background: ghostwhite; }
.list del { display: none; }
<div class="list">
  <div>1</div>
  <div>2</div>
  <div>3</div>
  <del>4</del>
  <div>5</div>
  <del>6</del>
  <div>7</div>
</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Having difficulty transferring data from a JSON file on a different domain to a variable using Ajax

As a beginner in Ajax, I am currently exploring the use of Ajax Cross domain functionality to fetch data. The Ajax function is triggered from test.php, which then calls stats.php to request the desired data. The content of Stats.php: <?php $data = ...

Is there a way for me to view the contents within the box?

Hey there! I have a question about how to access the content inside this mysterious box "" within the style sheet. For instance, I am curious to find out the link of the image: .facebookicon::before { content: ""; } ...

suggestions automatically populating in a text box as you type

I am looking to meet a small requirement where I need to retrieve all records from a table or store elements in a key-value pair format. This way, when a user types in the key, the corresponding value should be displayed. If the user presses the enter butt ...

Sending a directive as an argument to a parent directive function

edit: I made adjustments to the code based on stevuu's recommendation and included a plunkr link here Currently, my goal is to make a child directive invoke a method (resolve) through another directive all the way up to a parent directive. However, I ...

How can you ensure that text in a container automatically moves to a new line and causes the container to expand downward if necessary, when

Are you searching for a way to make text inside a container wrap to a new line and have the container expand downwards if needed? Update <div class="modal hide fade" id="modalRemoveReserve" style="display:none;"> <div class="modal-header"&g ...

Determining the distance between points in an STL file with three.js

I'm currently working on a feature that requires users to click on two different points and calculate the distance between them. However, it seems like the clicks are occurring at random positions, resulting in inaccurate calculations. The calculati ...

Convert individual packages within the node_modules directory to ES5 syntax

I am currently working on an Angular 12 project that needs to be compatible with Internet Explorer. Some of the dependencies in my node_modules folder are non es5. As far as I know, tsc does not affect node_modules and starts evaluating from the main opti ...

The jQuery code is failing to run as intended

Recently, I encountered an issue with a HTML page that utilizes some jQuery libraries. The specific functionality in question involves a balloon floating across the screen, which works perfectly fine on my local machine. However, upon integrating this pag ...

Problem with single-table layout in DynamoDB and constraints on query parameters

I'm trying to limit the elements I fetch in each query, but encountered an issue: Using the single-table design in DynamoDB, I am only getting four items. https://i.sstatic.net/N4wVS.png If I check the first 10 elements in DynamoDB, I always get a ...

"Exploring the world of remote_form_tag in Rails with jrails

After transitioning to jQuery with jRails for my application, most of my previous RJS code is working perfectly. However, I am facing an issue with the :loading => callback when using the remote_form_tag. <% form_remote_tag :url => '/hostels ...

How can I programmatically click the send button on WhatsApp using Selenium, either through xpath or css selectors in vb.net

Looking for help on using Whatsapp XPath or CSS with Chromedriver in VB.NET. HTML: <span data-testid="send" data-icon="send" class>...</span> ==$0 XPath: //*[@id="main"]/footer/div[1]/div/span[2]/div/div[2]/div[2 ...

After submitting a post, the click event of a button in IE 10 using jQuery is not

The uploadButton feature allows users to upload an image and store it locally. I utilize fileinput to select the image, and when uploadbutton is clicked, the image data is sent back to the server. While this functionality works smoothly in Chrome, I encou ...

How to convert deeply nested object structures containing arrays in JavaScript

Despite the less-than-desirable name of this inquiry, the question is fairly straightforward. I have a particular object: let test = { date1: [ { time: 1, value: 5, }, { time: 2, value: 6, }, ], date2: [ { ...

Utilizing the text field feature within Twitter Bootstrap 3.0 in-line styling

I am attempting to create a horizontal form with an inline text field split into two sections: one on the left and one on the right. The left side will contain horizontal text fields, some of which are inline, while the right side will have a mix of inline ...

Issue with AjaxComplete function failing to work

Currently, I am tackling the Opera workaround for printing IFrames. As we are aware, the only method to print an IFrame is by opening it in a new window and then printing it. However, I am encountering an issue where a series of ajax calls are triggered wh ...

A step-by-step guide on showcasing three post images in separate divs at the bottom of a webpage with Reactjs and Css

In the array below, there are three post photos. When I click on each post button, I should see a corresponding post photo div at the bottom for each post. Issue: I am facing a problem where only one post photo div is being displayed, which keeps replaci ...

The rendering of the .Net MVC DropDownList is not displayed properly when it is first set to be hidden

Exploring the realm of .Net MVC is a new adventure for me, and I'm hoping that resolving this issue will be straightforward. In my project, there's an HTML table row that should remain hidden upon page load but become visible once a specific opt ...

NextJs not processing Bootstrap form submissions

I’m struggling to figure out why my form isn’t submitting when I click the submit button. The backend seems fine because Postman successfully sends the information to the database. However, nothing happens when I try to submit the form. My tech stack ...

Conceal navigation buttons on the first and last pages of the slider

I'm attempting to develop a slider that hides the "previous" button when it is on the first slide and hides the "next" button when it reaches the last slide. The slider will be created using a combination of PHP, forms, and JavaScript. Below is the H ...

Transmit information to the server via an AJAX request

$.ajax({ url:"http://192.168.0.74:8080/pimsdesign/JSONRequestHandler" , type: "POST", data: {name: "amit", id:1 }, dataType: "json", beforeSend: function(xhr) { if (xhr && xhr.overrideMimeType) { xhr.overrideMimeType("application/json;charset=UTF-8 ...