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

Crafting a horizontal sub-menu that sits between the parent element and the company logo

Seeking assistance with designing a navigation menu that places the navigation bar above the site logo. I envision the sub-menu expanding horizontally from the navigation bar and positioning itself between the parent navigation bar and the logo. The sub- ...

Prevent users from inputting multiple minus signs by setting the input type to number and disabling the

Is there a way to prevent the input type number from accepting "--" as input? I am looking for a solution to disable this behavior. Additionally, the input field seems to allow for various incorrect formats like: -12-12 -- -121- 23-323- ...

Adding a class to an img tag with TinyMCE

Currently, I am utilizing the TinyMCE editor as a standalone editor in my content management system (CMS). Within the CMS, there is an automatic setting that adds a curved border to any image tags within the cms div ID. In certain cases, I require the op ...

What is the reason behind getElementsByClassName not functioning while getElementById is working perfectly?

The initial code snippet is not functioning correctly DN.onkeyup = DN.onkeypress = function(){ var div = document.getElementById("DN").value document.document.getElementsByClassName("options-parameters-input").style.fontSize = div; } #one{ heigh ...

Starting the animation only when the slide is visible

Struggling to add animations dynamically as a HTML/CSS developer who avoids JS but uses jQuery occasionally? Sound familiar? Well, I have. Recently, I managed to create a CSS-3 animation for the images in a Bootstrap carousel. Check out the code below: ...

Chrome is experiencing compatibility issues with Datatable

I'm encountering an issue with Datatables and I'm at a loss on how to resolve it. In my custom cms, Datatables functions perfectly on my Mac (Safari, Chrome, Firefox) and also works seamlessly for my colleagues on Windows machines. However, we ...

Unable to alter or eliminate the grey background using material-ui

Struggling with a React application that incorporates material-ui. Despite my efforts, I can't seem to get rid of an unwanted grey background in one section of the app. Attempted solutions: body { background-color: #ffffff !important; } * { b ...

"Illuminating the way: Adding a search bar to your

Looking to enhance my WordPress blog with a search bar, I opted for a generic HTML approach over using get-search-form(). Here is the code snippet from my theme: <div class="input-group"> <input type="text" class="form-c ...

Conceal elements on smaller screens using the Bootstrap 5 grid system

I'm facing a design issue with my layout - it looks perfect on larger screens but when viewed on mobile devices, the columns stack vertically instead of horizontally. Essentially, I want to hide the first and second last column on small screens and r ...

Transferring information to the controller and refreshing the interface (Single-page design)

I'm stuck on a personal project and could really use some help. If anyone has any feedback, it would be greatly appreciated. Thanks in advance. In my index.php file, I have a div with the id main-container. Inside this container, there are two separa ...

What is the best way to find a specific class within a CSS file using Visual Studio Code?

Currently, I am working with a bootstrap template on my webpage. I am interested in personalizing specific sections of the design, but unfortunately, I am having trouble identifying the relevant CSS rules within the extensive .css file. My research online ...

Unable to shift the header menus upwards for proper alignment with the logo

Header with logo I'm trying to align the menu items like Home, etc with the logo, but it seems like the logo is taking up too much space above the menu headers and I'm not sure how to reduce it. I've already attempted using margin-left or r ...

Tips for maintaining the active tab in Jquery even after the page is reloaded, especially for tabs that are constantly changing

$(document).ready(function(){ $('.scroll_nav li a').click(function(){ $('li a').removeClass("active_scroll"); $(this).addClass('active_scroll'); $('ul li .btn-br_all_gun').click(function(){ ...

Creating geometric designs on an image and storing them using PHP

I am attempting to retrieve an image from a specific location on my server, draw lines on it, and then save the modified image back to the same location. Below is the code I am using: function drawShapes($src_path, $json) { echo "---inside dra ...

Adding multiple elements with varying content to a separate division

I am attempting to combine two div elements into a single div, but I'm encountering difficulties. Despite thoroughly examining my code, everything appears to be correct. Here's what I've tried so far. To assist me in achieving this, I am ut ...

Toggle classes on button click

<div class='fixed_button homes hidden'> <a class='btn btn-primary homes'>Continue &rarr;</a> </div> Using jQuery Library $(".homes").on('click', function(){ $("choose_style").addClass(&apo ...

Displaying information from an array using AngularJS

I'm struggling to display data from an array and I could use some help. Here's a snippet from my service.js file: this.fetchData = function() { var myArray = $resource('url', {method: 'get', isArray: true}); myArray ...

How can I use CSS to position one div on top of another div, without it moving when the page is scrolled down?

I have two images, one rectangle and one circular. The rectangle image needs to be positioned 10em lower due to a banner image at the top. Half of the circle should overlap with the rectangle while the other half remains outside. The center of the circle m ...

The tooltip for the Google+ button stopped working

After setting up my Portfolio, I added a Google+ button. However, the page lacks styling and there seems to be an issue with the tooltip causing delays. Can anyone help me identify where the problem lies? ...

Sending values to URL using the <a> tag in HTML

I currently have the selected language stored in a variable (var lan= urlParam('language')). I am trying to pass this language as a parameter (without PHP) in a URL within an "a" tag, like so: <a href="http://hotelscombined.sitewish.gr/HotelN ...