Using CSS nth-of-type on the same level of the DOM allows for specific

I was having trouble using the nth-of-type(2n+1) selector to target odd and even rows in the scenario below. What I wanted was for the nth-of-type selector to apply different styles to the odd rows with the classes "row-data row-header" and "row-data row-content." Eventually, I had to resort to using jQuery upon document load to manually add an "odd" class to certain rows. Is there a more efficient (CSS-only) method for achieving this?

This is my desired CSS:

.row-data.row-header(2n+1) .col { background-color: #e7e7e7; }
.row-data.row-content(2n+1) .col { background-color: #c8ebed; }

Despite trying variations like using "odd" instead of 2n+1, the above CSS did not produce the desired results. As a workaround, I implemented the following JavaScript logic:

<script>
    function alternateRowBackgroundColours()
    {
        $(".row-header").each(function (i, e)
        {
            if (i % 2 != 0)
                $(this).addClass("odd");

            $(".row-content", $(this).next(".row-cnt")).each(function (j, e)
            {
                if (i % 2 != 0)
                    $(this).addClass("odd");
            });
        });
    }

    $(document).ready(function ()
    {
        alternateRowBackgroundColours();
    });
</script>

Corresponding to the script, I then included the following CSS:

.row-data.row-header.odd .col { background-color: #e7e7e7; }
.row-data.row-content.odd .col { background-color: #c8ebed; }

It should be noted that the number of row-header(s) and their associated row-content(s) is dynamic, and each row-header has a toggle button that reveals its corresponding row-content(s) similar to an accordion.

The outcome of implementing these changes can be visualized https://i.sstatic.net/MuMzT.jpg.

Answer №1

Due to the hierarchical structure of all rows as siblings, it is important to differentiate between header and content rows using specific selectors:

.row-header:nth-child(4n+1) {
  background-color: red;
}

For the internal content rows, a different selector should be used:

.row-cnt > div:nth-child(odd){
  background-color: #999;
}

Inspect this code snippet:

body {
  font-family: sans-serif;
  font-size: 14px;
}
.row-cnt > div{
  background-color:#f1f1f1;
  padding:3px;
}
.row-cnt > div:nth-child(odd) {
  background-color: #999;
}
.row-header {
  color: white;
  background-color: blue;
  font-size: 1.5em;
  padding: 10px;
}
.row-header:nth-child(4n+1) {
  background-color: red;
}
<div class="row row-data row-header">
  <div class="col col-sm-12 col-md-12">
    <!-- HEADER CONTENT ... -->
    My header 1
    <a class="btn btn-primary btn-sm btnToggleContent" onclick="toggleRowContent(this)"><i class="fa fa-chevron-right toggleIcon"></i></a>
  </div>
</div>
<div class="row row-cnt">
  <div class="row row-data row-content">
    <div class="col col-sm-12 col-md-12">
      <!-- ROW CONTENT -->My content 1.1</div>
  </div>
  <div class="row row-data row-content">
    <div class="col col-sm-12 col-md-12">
      <!-- ROW CONTENT -->My content 1.2</div>
  </div>
  <div class="row row-data row-content">
    <div class="col col-sm-12 col-md-12">
      <!-- ROW CONTENT -->My content 1.3</div>
  </div>
</div>
<div class="row row-data row-header">
  <div class="col col-sm-12 col-md-12">
    <!-- HEADER CONTENT ... -->
    My header 2
    <a class="btn btn-primary btn-sm btnToggleContent" onclick="toggleRowContent(this)"><i class="fa fa-chevron-right toggleIcon"></i></a>
  </div>
</div>
<div class="row row-cnt">
  <div class="row row-data row-content">
    <div class="col col-sm-12 col-md-12">
      <!-- ROW CONTENT -->My content 2.1</div>
  </div>
  <div class="row row-data row-content">
    <div class="col col-sm-12 col-md-12">
      <!-- ROW CONTENT -->My content 2.2</div>
  </div>
</div>
... (additional rows omitted for brevity)

Answer №2

Try using nth-child instead of nth-of-type to specifically target odd numbers within your local elements.

.row.row-data.row-header:nth-child(odd) {
    /* your styles here */
}

.row.row-data.row-header:nth-child(odd) {
  background: red;
}
.row.row-data.row-content:nth-child(odd) {
  background: green;
}
<div class="row row-data row-header">
  <div class="col col-sm-12 col-md-12">
    <!-- HEADER CONTENT ... -->
    My header 1
    <a class="btn btn-primary btn-sm btnToggleContent" onclick="toggleRowContent(this)"><i class="fa fa-chevron-right toggleIcon">icon</i></a>
  </div>
</div>
<div class="row row-cnt" style="">
  <div class="row row-data row-content">
    <div class="col col-sm-12 col-md-12">
      <!-- ROW CONTENT -->My content 1.1</div>
  </div>
  <div class="row row-data row-content">
    <div class="col col-sm-12 col-md-12">
      <!-- ROW CONTENT -->My content 1.2</div>
  </div>
  <div class="row row-data row-content">
    <div class="col col-sm-12 col-md-12">
      <!-- ROW CONTENT -->My content 1.3</div>
  </div>
</div>
<div class="row row-data row-header">
  <div class="col col-sm-12 col-md-12">
    <!-- HEADER CONTENT ... -->
    My header 2
    <a class="btn btn-primary btn-sm btnToggleContent" onclick="toggleRowContent(this)"><i class="fa fa-chevron-right toggleIcon">icon</i></a>
  </div>
</div>
<div class="row row-cnt" style="">
  <div class="row row-data row-content">
    <div class="col col-sm-12 col-md-12">
      <!-- ROW CONTENT -->My content 2.1</div>
  </div>
  <div class="row row-data row-content">
    <div class="col col-sm-12 col-md-12">
      <!-- ROW CONTENT -->My content 2.2</div>
  </div>
</div>

Answer №3

take a look at this code excerpt

div.row-data.row-header:nth-of-type(2n+1){
  display:block;
  background:red;
}

div.row-data.row-content:nth-of-type(2n+1){
  display:block;
  background:green;
}
<div class="row row-data row-header">
    <div class="col col-sm-12 col-md-12">
        <!-- HEADER CONTENT ... -->
        My header 1
        <a class="btn btn-primary btn-sm btnToggleContent" onclick="toggleRowContent(this)"><i class="fa fa-chevron-right toggleIcon">hello</i></a>
    </div>
</div>
<div class="row row-cnt">
    <div class="row row-data row-content">
        <div class="col col-sm-12 col-md-12"><!-- ROW CONTENT -->My content 1.1</div>
    </div>
    <div class="row row-data row-content">
        <div class="col col-sm-12 col-md-12"><!-- ROW CONTENT -->My content 1.2</div>
    </div>
    <div class="row row-data row-content">
        <div class="col col-sm-12 col-md-12"><!-- ROW CONTENT -->My content 1.3</div>
    </div>
</div>
<div class="row row-data row-header">
    <div class="col col-sm-12 col-md-12">
        <!-- HEADER CONTENT ... -->
        My header 2
        <a class="btn btn-primary btn-sm btnToggleContent" onclick="toggleRowContent(this)"><i class="fa fa-chevron-right toggleIcon"></i></a>
    </div>
</div>
<div class="row row-cnt" style="display: none">
    <div class="row row-data row-content">
        <div class="col col-sm-12 col-md-12"><!-- ROW CONTENT -->My content 2.1</div>
    </div>
    <div class="row row-data row-content">
        <div class="col col-sm-12 col-md-12"><!-- ROW CONTENT -->My content 2.2</div>
    </div>
</div>

Trust you find this information useful

Answer №4

Consider utilizing the odd keyword for better results.

.row-data.row-content:nth-of-type(odd) {

}

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

I am curious if there is a feature in intro.js that allows for the highlighting of text or images to

I am having trouble getting intro.js to work with Ionic 4 as the highlighted text is not showing up view image here This is how I implemented the code in Angular 7: intro() { let intro = introJs.introJs(); intro.setOptions({ exitOnOverlayClick: false, ...

The merging of several XSL files

Hey there, I have two separate xsl files and an xml file. Is there a way to merge these xsl files into one transform type to create a single HTML output? The first xsl file is called index.html: <?xml version="1.0" encoding="ISO-8859-1"?> <!DOCT ...

Issue with vue-template-compiler in Vue.js 3 webpack configuration

I am currently working on integrating vuejs 3 into a project that already utilizes webpack. I have been looking into using vue-loader as part of this process. After consulting the official documentation, I came across the following information: Every new ...

Deactivate while maintaining menu options

Currently, I have a Vue.js form that manages adding and updating data for patients. The issue at hand involves a <select> tag which allows for the addition of a relative. This select field is populated by an array called PPrelations, which is sourced ...

Adding a new entry to a database that involves many-to-many relationships

I recently inquired about executing a fetch query on a database with a many-to-many relationship. As I delve deeper into learning SQL + PHP, I encountered a rather intricate scenario: Within my database, I have the following tables: Songs Link ...

Exploring and accessing the properties of objects in JavaScript

While attempting to access the email and password fields, an unexpected '0' seems to have appeared. The object retrieved from RethinkDB appears fine without this '0'. However, when using Lodash's _.assign() method like so: var use ...

concerns with Ajax-based pagination techniques

I've successfully implemented ajax pagination in codeigniter. However, I am facing an issue where the records are divided by 10 and the page automatically reloads when I click on the next page button. This functionality works fine on localhost but not ...

Unable to adjust the width of a table column within a horizontally scrollable container

I am struggling to resize the columns of a large table with 20 headers. Despite trying to place the table inside a div with overflow:auto, I still cannot achieve horizontal scrolling or make the div expand when resizing the columns. A sample code snippet ...

The initialization of the Angular service is experiencing issues

I have a service in place that checks user authentication to determine whether to redirect them to the login page or the logged-in area. services.js: var servicesModule = angular.module('servicesModule', []); servicesModule.service('login ...

Utilizing Custom Validators in Angular to Enhance Accessibility

I'm struggling to access my service to perform validator checks, but all I'm getting is a console filled with errors. I believe it's just a syntax issue that's tripping me up. Validator: import { DataService } from './services/da ...

What is the proper way to leverage the global 'window' object within Angular?

I'm attempting to utilize the method "window["initMapCallback"]" to invoke and monitor for "initMapCallback" in a separate file. However, I am encountering an error message in the debugging console that states Query - How can I properly implement thi ...

Vue 3 has a known issue where scoped styles do not get applied correctly within the content of a <slot> element

Utilizing the Oruga and Storybook libraries for creating Vue 3 components. The code in the Vue file looks like this: <template> <o-radio v-bind="$props" v-model="model"> <slot /> </o-radio> </template ...

Leveraging Vue slots to display a component inside another component

I am currently working on creating a base modal component that can be re-used, utilizing slots to insert the modal content. The issue I am facing is that when the modal is triggered by clicking a button, it displays without any content present. How can I e ...

Utilizing jQuery to create a recursive AJAX poll with setTimeout to regulate the polling frequency

$(document).ready(function() { (function pollUsers() { setTimeout(function() { $.ajax({ url: "/project1/api/getAllUsers", type: "GET", success: function(userData) { ...

Ways to ensure a <div> element adjusts its height based on inner content dimensions

When using buttons in a chatbot that have text which changes based on selected options, I've encountered an issue where the text length sometimes exceeds the button's space. I'm looking for a way to make the containing div automatically adj ...

An instructional guide on utilizing Python to extract the URLs of companies from a LinkedIn search

I'm having an issue extracting company profile URLs from a LinkedIn search as I keep getting a "not found" message. Despite my code running smoothly, the problem persists. Here is my code: import requests import csv import time import numpy from bs4 ...

When using a Vue.js component, the value of this.$route can sometimes come back

I am attempting to retrieve the parameters from the URL and pass them into a method within a Vue component. Despite following advice to use this.$route, I am consistently getting an 'undefined' response. I have tried various solutions suggested ...

Having trouble installing sqlite3? Encounter an issue like this: "srcdatabase.cc(35): error C2248: 'Napi::Env::DefaultFini': cannot access private member declared in class 'Napi::Env'"?

Encountering issues while trying to install sqlite3 for a Strapi app I've attempted using yarn to install sqlite3 in various ways, but to no avail. Below is the error log: Error message: Issue with installing sqlite3 when creating a Strapi app (..& ...

A plethora of options for popup modals in jQuery, including stacked modals and various alternative modal

Is there an alternative to using multiple modals? I require the ability to have multiple instances of modals. Upon clicking "Open modal" on the main page, a form modal (Modal-A) should open, with a link inside Modal-A that can open another modal (Modal-B) ...

What is the best way to pass cookies between domain and subdomain using nookies?

Recently, I've been facing some challenges with sharing cookies between my app and website while using nookies. Below is the code snippet from my app.mydomain.com file: //setCookies to main domain setCookie(null, 'jwt', login ...