Is it possible to utilize CSS :nth-child (or a similar method) to target groups of elements in HTML, like selecting every fourth node alternately?

Let me give you a bit of background: I'm currently working on creating a layout where the elements flow from left to right in one row, then switch to flowing from right to left in the next row, and so on. To better illustrate what I mean, I have created a mockup in CodePen, which you can check out by following the link.

To achieve this layout, I have used the CSS property nth-child, but it's a bit 'hardcoded', for example:

Here's a snippet of the HTML:

<ul>
  <li>1</li>
  <li>2</li>
  ...
  <li>16</li>
</ul>

And here's the corresponding CSS:

li { float: left; }

li:nth-child(5),
li:nth-child(6),
li:nth-child(7),
li:nth-child(8) {
  float: right;
}

While this method works, it is limited to a specific number of elements (as defined in the CSS). I know that I can use :nth-child(4n) to target every fourth element, but what I really want is to target not just one group of four elements, but also the following group of four. It's almost like using nth-child(odd), but for groups of 4 elements.

Is there a way to achieve this programmatically? I've looked into Quantity Queries (), but it doesn't seem to be exactly what I need...

I would greatly appreciate any help or guidance on this matter! Thank you!

Answer №1

A group of nth-child selectors can be utilized, as shown in the snippet below, to target a repeating set of elements following a certain pattern.

It's important to understand that selecting every 3rd element and the subsequent 3 elements is essentially equivalent to selecting all elements beyond the 3rd one. For demonstration purposes, the sample has been limited to just the following 2 elements.


Detailed breakdown of the selector (selects 3rd, 4th, 7th, 8th elements, and so forth):

  • nth-child(3n+3) - targets the 3rd (3*0 + 3), 6th (3*1 + 3), 9th (3*2 +3) elements
  • nth-child(3n+4) - targets the 4th (3*0 + 4), 7th (3*1 + 4), 10th (3*2 + 4) elements

This breakdown illustrates that the series commences from the 3rd element and continues in repetition thereafter. If you require the sequence to initiate from the 1st element (like 1st, 2nd, 5th, 6th etc.), you could employ the selector pairing of

div:nth-child(3n+1), div:nth-child(3n+2)
.

div:nth-child(3n+3), div:nth-child(3n+4){
  color: blue;
}
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>
<div>6</div>
<div>7</div>
<div>8</div>
<div>9</div>
<div>10</div>
<div>11</div>
<div>12</div>


Detailed breakdown of the selector (targets 3rd, 4th, 11th, 12th elements, etc.):

  • nth-child(7n+3) - selects the 3rd (7*0 + 3), 10th (7*1 + 3), 17th (7*2 +3) elements
  • nth-child(7n+4) - selects the 4th (7*0 + 4), 11th (7*1 + 4), 18th (7*2 + 4) elements

Similar to the prior explanation, this breakdown signifies the initiation of the series from the 3rd element, repeating subsequently. To start the series from the 1st element (such as 1st, 2nd, 5th, 6th, etc.), the selector combination could be

div:nth-child(3n+1), div:nth-child(3n+2)
.

div:nth-child(7n+3), div:nth-child(7n+4){
  color: blue;
}
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>
<div>6</div>
<div>7</div>
<div>8</div>
<div>9</div>
<div>10</div>
<div>11</div>
<div>12</div>
<div>13</div>
<div>14</div>
<div>15</div>

Answer №2

Furthermore, when wanting to choose the children 5,6,7,8 within a group of 16, you can employ

:nth-child(n+5):nth-last-child(n+9)

Perhaps you will discover the functionality on your own 😉

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

Unable to modify the appearance of an HTML element when injected via a Chrome extension

I am currently developing a unique chrome extension that uses Ajax to inject custom HTML into the current tab. This extension appends a <div> element to the body, and now I need to manipulate it using JavaScript. Specifically, I want it to dynamical ...

Craft an engaging and dynamic Image map with SVG technology to elevate responsiveness and interactivity

I'm currently working on a website and I need to create two clickable sections on the home page. Each section will lead to a different specialization of the company. To achieve this, I decided to use a square image split into two right-angled triangle ...

Challenge encountered in handling AJAX response data for presentation

Currently, I am immersed in a project and decided to implement AJAX for smoother form submissions. My initial attempt was trying to display text from a .txt file below the "submit" button, but unfortunately, that approach didn't yield the desired resu ...

Chrome introduces surprise spacing to text input fields styled uniquely

This particular code snippet is functioning correctly on Firefox, but unfortunately not on Chrome. The height of the input should match the styling of the select, but there seems to be a discrepancy in Chrome. Any ideas on how to rectify this? Upon closer ...

Using a Jquery selector with either the ID Regex or a repetitive class

There is a collection of similar elements with matching IDs Below are two methods for selecting them using Jquery: Select by ID + Regex (For example, How can I select an element by ID with jQuery using regex?) Add a redundant class to all the elemen ...

Making a request to an API using the useEffect hook resulted in an error when attempting to iterate through the list of users. The error message displayed was: TypeError: Cannot read property

import logo from './logo.svg'; import './App.css'; import { useEffect, useState } from 'react'; import User from './components/User/User'; function App() { const [user, setUser] = useState([]); useEffect(() => ...

Developing a responsive navigation bar for mobile devices

Can anyone help me with creating a mobile navbar that shows the hamburger icon on smaller screens? I would like the links to appear in blocks when the icon is clicked. I attempted to make it using an SVG icon for the hamburger and setting the display to n ...

Ways to prevent text from wrapping in CSS

I'm currently in the process of creating a new website and I've encountered an issue with my CSS. It seems that whenever there is a space present, the text inside h2 tags wraps unexpectedly. You can visit the site here. Here's the specific ...

Offspring of a parent with a "flex: 1" attribute and a grandparent with a "min-height" property defying the "width: 100%" rule

Is it possible to have a hidden footer just below the screen's bottom and allocate the remaining height to content children without inheriting max-height all the way down? The "Grand child" element is not occupying the full height: body { marg ...

Reduce the gap between the content and footer

I'm currently designing a homepage for a press release. I'm facing an issue with a large gap between my content and the footer, which I'd like to reduce. I've tried adjusting the margin-top: 0px in CSS with no success. Various attempts ...

Add a blur effect to a specific region of an SVG image

I have a complex, dynamic SVG image created using jQuery SVG. I want to create a "popup" area that appears on top of all SVG elements in the canvas. To achieve a modern translucent iOS7 style, I would like to add a blur filter to everything beneath the pop ...

attribute alternativeType

<input type="text" name="date" value="" data-type="datetime" required="true" /> I'm looking for a different approach than using dojoType for a couple of reasons: The parseonload behavior causes the page to "jump" when loading (system-defaul ...

Confirm that the CSS syntax is valid

Is there a way to validate CSS syntax by checking for specific characters like "{", "}", ";", and ":"? I have come up with four checks to ensure the code is valid, such as verifying that the number of opening and closing curly braces match, as well as the ...

Cities cannot be obscured by a rotating globe

In my latest project, I have created a jsfiddle showcasing a Bostock spinning globe implementation. After successfully plotting a few city markers, I encountered a problem where not all cities were being displayed. Additionally, the script intended to hid ...

Having trouble applying custom CSS styles to images in CarouselItem using Reactstrap? Learn how to use a div instead of an image for a solution

Currently, I am utilizing reactstrap in my live website powered by react.js. I am seeking assistance on how to implement the reactstrap carousel. Specifically, I am struggling with applying CSS directly to the image within CarouselItem. Since there is a s ...

Tips for creating a sticky bootstrap column that remains in place as you scroll

I am looking to design a FAQ page similar to Twitter's FAQ. The goal is to have the left column remain fixed in its position while allowing users to scroll through the content. Here is what I have attempted so far, but it is not functioning as expect ...

Is it possible to divide searches into separate divs?

How can I display the results of my AJAX live search in different result divs for styling purposes? I want to style the results separately and have them appear one at a time. However, the current setup with 'element.style' is causing issues. Is ...

css background is repeating after the height of the div is reset

I'm working on a project where I want to resize an image while maintaining its aspect ratio to fit the height/width of the browser window. However, every time the code for resizing is implemented, the div height continues to increase with each resize ...

Every time I reload the page, the id of the input box changes, making it a challenge to select it using Selenium in Python

HTML: <input id="4432e17d-eed6-4620-9bb4-d75ffbd321fa" type="email" placeholder="Email address" value="" name="emailAddress" data-componentname="emailAddress" autocomplete="email" aut ...

Shifting Bootstrap Columns into a New Configuration

I need to reorganize the columns on my bootstrap website. Currently, I have four images displayed like this: However, when the screen size is reduced below 768px, I want them to be rearranged as follows: I considered using bootstraps push-pull feature, b ...