How can I specifically target and count children from a certain class using CSS selectors?

Consider this HTML structure with items arranged at the same level:

<div class="h2">Title: Colors</div>
 <div class="pair">Hello world (1)</div>
 <div class="pair">Hello world (2)</div>
 <div class="pair">Hello world (3)</div>
 <div class="pair">Hello world (4)</div>
 <div class="pair">Hello world (5)</div>
 <div class="pair">Hello world (6)</div>

<div class="h2">Title: Units</div>
 <div class="pair">Hello world (1)</div>
 <div class="pair">Hello world (2)</div>
 <div class="pair">Hello world (3)</div>
 <div class="pair">Hello world (4)</div>
 <div class="pair">Hello world (5)</div>
 <div class="pair">Hello world (6)</div>

How can I target and style the n+3 and n+4 .pair elements following the previous .h2 element?

This means 1&2 are white, 3&4 are pink, 5&6 are white, and so on.

I attempted to use

.pair:nth-child(4n+3), .pair:nth-child(4n+4) { background: #FFAAAA; }
, but it includes the children of the body where the h2 elements also exist, disrupting the desired styling balance.

http://jsfiddle.net/zPYcy/2/


Edit: No pure CSS selector exists to efficiently select adjacent items in a pattern like .class (n+3). As an alternative, a series of CSS selectors using

div + .class + .class + .class ...
; combined with :nth-child(n+3) or :nth-of-type(n+3); or utilizing JS is necessary. Do you know any other workaround? Your input is appreciated!

Answer №1

This solution utilizes a combination of the sibling, nth-child, and nth-last-child selectors.

For each div with the class h2, an additional class "colors" and "units" should be added as follows:

<div class="h2 colors">Title: Colors</div>
...
<div class="h2 units">Title: Units</div>
...

The rule is applied to all children that have a preceding sibling with classes h2 and colors, styling the divs in pink:

.h2.colors ~ .pair:nth-child(4n+4), .h2.colors ~ .pair:nth-child(4n+5) { 
    background: #FFAAAA; 
}

To prevent the styling from affecting divs below h2 units, two rules are applied in reverse order up to h2 units:

.h2.units ~ .pair:nth-last-child(4n+3), .h2.units ~ .pair:nth-last-child(4n+4) { 
    background: #FFAAAA; 
}

To address any extra divs styled by the first rule, a white background is applied:

 .h2.units ~ .pair:nth-last-child(4n+1), .h2.units ~ .pair:nth-last-child(4n+2) { 
        background: #ffffff; 
    }

It's important to consider the odd or even number of divs in the last group when using the nth-last-child selector.

Check out this fiddle for experimentation.

Answer №2

If we are looking to target specifically the 3rd and 4th pairs following each occurrence of an .h2 element, this code snippet will do the trick:

.h2 + .pair + .pair + .pair,
.h2 + .pair + .pair + .pair + .pair { background: #FFAAAA; }

However, if we want to maintain the pattern of selecting every 2nd pair in a longer list, a different approach is needed.


UPDATE: To ensure our solution is scalable, we can slightly modify the HTML markup by enclosing each set of .pair items within another class:

<div class="h2 colors">Title: Colors</div>
<div class="pairList">
    <div class="pair">Hello world</div>
    <div class="pair">Hello world</div>
    <div class="pair">Hello world</div>
    <div class="pair">Hello world</div>
    ...
</div>

By utilizing the CSS rule below, we can apply styles to any number of items seamlessly:

.pairList .pair:nth-of-type(4n+3), 
.pairList .pair:nth-of-type(4n+4) { 
    background: #FFAAAA; 
}

Check out this FIDDLE for demonstration

Answer №3

Due to a combination of sheer boredom and unrelenting curiosity, I decided to craft a function for this very purpose. If you find yourself in a situation where the HTML structure is fixed and you have multiple extended rows, my custom plugin may just come in handy.

To implement the function, simply retrieve it from my jsFiddle and utilize it as shown below:

var item1 = locateRelative('h3', 'item', '5n+2');
var item2 = locateRelative('h3', 'item', '5n+4');
var result = item1.add(item2);

You have the flexibility to modify the parameters h3 and item with different class names, or experiment with various patterns that include #n, and optionally

+#</code resembling the CSS nth child selector. Adding <code>false
as a fourth argument...

locateRelative('title-header', 'content-block', '2n', false);

...will target all elements following the initial occurrence of title-header based on the specified pattern, rather than after every single instance of content-block.... if that makes any sort of sense.

I am aware that sh0ber has devised a more practical solution, but creating this function was an enjoyable endeavor that I felt compelled to share with others.

http://jsfiddle.net/ABC123/9/

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

Creating dynamic and interactive web pages can be achieved by utilizing either $_POST or $_GET with Modal,

In the snippet below, you'll find the HTML code that pulls an array of 6 objects from a database and displays them in a Bootstrap row successfully. <div class="row products"> <?php while($product = mysqli_fetch_assoc($featured)) ...

jquery script that retrieves the href attribute of the anchor tag located near the button that is currently being clicked

Hello there! I am trying to extract the href of a link when the button next to it is clicked by the user. However, the challenge is that there are multiple buttons and links on the page. For example, if the first button is clicked, I want to display "www. ...

When the window is resized, the nested div parent and child are overlapping

Is there a way to fix the issue of the content div overlapping the logo div when resizing the browser window? I would like the logo to resize along with the window. @charset "utf-8"; /* CSS Document */ html, body { background-color:#ffffff; mar ...

Arranging rows of a specific height within a table at any location

I need to create a virtual table to browse through a very large dataset. Is there a way to position the rows (with fixed height) anywhere within the table? The issue I am facing is that the table properties automatically adjust the row height, disregarding ...

At times, the CSS fails to load at first and does not refresh correctly when using F5 or CTRL F5, yet it occasionally loads when clicking on links

After dedicating a full day to trying to solve this issue, I am reaching out for some assistance. As a newcomer here, I apologize if this question has been asked before (I did search extensively and found nothing). The website I'm constructing for my ...

Getting the value of a JavaScript variable and storing it in a Python variable within a Python-CGI script

Is there a way to capture the value of a JavaScript variable and store it in a Python variable? I have a Python-CGI script that generates a selection box where the user can choose an option from a list. I want to then take this selected value and save it ...

Preventing the display of AngularJS HTML tags while the app is being loaded

I am new to AngularJS (using version 1.5.8) and I am currently following the tutorials provided on docs.angularjs.org/tutorial. Below is the HTML code snippet: <div class="jumbotron"> <h1>{{application_name | uppercase }}</h1> ...

What are the steps to effectively utilize my search bar alongside Google Custom Search?

Here is the HTML code for my form: <form action="#" class="searh-holder"> <input name="se" id="se" type="text" class="search" placeholder="Search.." value="" /> <button class="search-submit" id="submit_btn"><i class="fa fa-sea ...

Step-by-step guide on creating a linear graph in CSS using a table

I am a newcomer to the world of CSS and I am looking to create a graph using CSS without the use of any libraries or frameworks. Can someone kindly assist me in drawing a linear graph using this HTML table? Appreciate any help in advance. <html> & ...

Switch Image on Hover in Panel Group

After delving into Bootstrap, I encountered an issue. I have a Panel-Group with an image and some text. The challenge is switching the image on hover, but it should change when hovering over the panel, not just the image itself. I've found solutio ...

How do Box and Grid components differ in Material-UI?

Can you please explain the distinction between Box and Grid in Material-UI? How do I know when to use each one? I'm struggling to understand their differences. ...

Basic JavaScript framework centered around the Document Object Model (DOM) with a module structure similar to jQuery. Currently facing challenges with

In order to create a simple framework with jQuery style, I have written the following code: (function(window) { window.smp=function smpSelector(selector) { return new smpObj(selector); } function smpObj(selector) { this.length = 0; if (!s ...

Issue with SideNav function in MaterializeCss following recent update

After updating the css/js files of the Materializecss design in my project from v0.97.5 to v0.97.8, I noticed that my SideNav isn't functioning correctly anymore. When I try to click on the menu, it slides out but the dark overlay covers the entire sc ...

How to optimize form fields in Bootstrap by utilizing the size/maxlength attributes in HTML inputs

When I attempted to utilize html5's form size/maxlength with bootstrap, I encountered an intriguing issue. The .form-control class in bootstrap overrides the size, but if removed, the input loses its styling. Check out the code pen here: http://code ...

Innovative CSS techniques and outdated web browsers

Do you think it's beneficial to incorporate cutting-edge CSS-properties such as border-radius, text-shadow, box-shadow, and gradient into your layout designs today? And how about utilizing values like rgba()? As I explore various web galleries, I not ...

AngularJS - varying actions based on which input field I interacted with first

Here is the tutorial I referenced for this code: <!DOCTYPE html> <html> <head> <title>AngularJS Tutorials</title> <link rel="stylesheet" href="vendor/foundation/foundation.min.css"> </head> <body> & ...

Potential Issue with CSS General Sibling Selector

It seems like I have encountered a potential bug with the General Sibling Selector. When I use p ~ div, the selector does not work as expected. However, when I replace p with the specific class name text_paragraph, it works fine. You can view my code and f ...

Using CSS to cut out a triangle shape from an image

Our designer has a vision for this: However, I'm struggling to find a suitable method for creating the triangle crop effect: Implementing an :after element that spans the entire width and utilizes border tricks to form a triangle shape Creating a l ...

What is causing my button to act in this way?

Initially, the website redirects to an undefined URL and then to test.com. I am looking for a way to implement a redirection sequence from to and finally to <head> <script type="text/javascript"> <!-- function popup(url ...

Adjust the Size of Bootstrap 4 Dropdown Caret Icon

Currently, I am using the Bootstrap v4 framework on my HTML page. I am looking to resize or increase the caret size in my dropdown list. Does anyone have any tips on how to accomplish this? Below is the code snippet: <div class="container"> <f ...