How can we use the nth-of-type selector to target a set of eight elements in a

I am trying to style a group of divs in such a way that every set of eight elements will have the same left positioning. Rather than just styling every eighth element individually, I want to apply the styling to groups of eight elements at once. However, my attempts using CSS and jQuery are only affecting every eighth element, which is not the desired outcome.

var cells = $('.board-cells'),
        cellUnit = 70,
        startPos = -35;

    var left;
    for(j=0; j<8; j++){
      left = startPos+(cellUnit*j+1) + 'px';
    }
    for(i=0; i<cells.length; i+=8){
      var cellItem = $('.board-cells:nth-of-type('+i+'n+0)');
      cellItem.css('left', left);
    }

Answer №1

If you want to create a grid layout, consider placing all the tiles inside an outer div with a fixed width. Each tile can then have a width that is approximately 1/7 of the outer div's width and be styled with float: left. By doing the math correctly, every eighth div will automatically move to the next row.

Learn more about floating divs (and clearing floats!) by visiting https://css-tricks.com/all-about-floats/. It's a great resource for mastering this technique.

Answer №2

What if we ditch the script and rely solely on CSS for this?

html, body {
  margin: 0;  
}
.container {
  display: flex;
  flex-wrap: wrap;
}
.container .img {
  height: 70px;
  width: calc(100% / 8);
  background: red;
  border: 2px solid white;
  box-sizing: border-box;
}
.container .img:nth-of-type(8n+1):after {
  content: '1';
}
.container .img:nth-of-type(8n+2):after {
  content: '2';
}
.container .img:nth-of-type(8n+3):after {
  content: '3';
}
.container .img:nth-of-type(8n+4):after {
  content: '4';
}
.container .img:nth-of-type(8n+5):after {
  content: '5';
}
.container .img:nth-of-type(8n+6):after {
  content: '6';
}
.container .img:nth-of-type(8n+7):after {
  content: '7';
}
.container .img:nth-of-type(8n+8):after {
  content: '8';
}
<div class="container">

      <div class="img"></div><div class="img"></div>
      <div class="img"></div><div class="img"></div>
      <div class="img"></div><div class="img"></div>
      <div class="img"></div><div class="img"></div>
      
      <div class="img"></div><div class="img"></div>
      <div class="img"></div><div class="img"></div>
      <div class="img"></div><div class="img"></div>
      <div class="img"></div><div class="img"></div>

    </div>


You can position each group by using a left value in your CSS

.container .img:nth-of-type(8n+1) {
  left: -34px;
}
.container .img:nth-of-type(8n+2) {
  left: 36px;
}
.container .img:nth-of-type(8n+3) {
  left: 106px;
}
.container .img:nth-of-type(8n+4) {
  left: 176px;
}
.container .img:nth-of-type(8n+5) {
  left: 246px;
}
.container .img:nth-of-type(8n+6) {
  left: 316px;
}
.container .img:nth-of-type(8n+7) {
  left: 386px;
}
.container .img:nth-of-type(8n+8) {
  left: 456px; 
}

Answer №3

Here is a potential solution for your problem:

let cellWidth = 70;
let startingPosition = -35;

$('.board-cells').each(function (index, element) {
    $(element).css('left', startingPosition + cellWidth * (index % 8) + 1 + 'px');
});

Check out the DEMO

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

Is there a way to detect if JavaScript is disabled using a unique CSS selector?

Does anyone know of a CSS selector that can be used when JavaScript is disabled? I'm not referring to the noscript tag, but specifically in CSS. ...

Issue: Compilation unsuccessful due to an error in the Babel loader module (./node_modules/babel-loader/lib/index.js). Syntax error

I'm currently exploring how to integrate the Google Maps Javascript API into my VueJs project without relying on the vue2-google-maps package (as it seems too restrictive to me). Here's what I've done so far, after registering my Vue compon ...

How can React hook state be efficiently utilized in a debounced callback?

function Foo() { const [state, setState] = useState(0); const cb = useCallback(debounce(() => { console.log(state); }, 1000), []); return ...; } In the code snippet above, there is a potential issue where the state variable may become outda ...

Attempting to bring in HTML through a helper, but Rails doesn't seem too thrilled about it

I have a form that triggers a remote GET request, leading to the display of a modal. The issue I'm facing is that multiple actions can utilize the same model, so I am attempting to employ a helper and jQuery to showcase different data based on what is ...

Is it possible to use a single validation rule for multiple fields in JQuery?

I have a question about JQuery validation and custom rules. I am new to this so please bear with me :) When using JQuery validation, if I want a textbox to be required, I can simply add the css class "required" to the element and it will be validated acco ...

How can I ensure that the background color of my HTML email blends seamlessly with the color of the email client's background?

As I embark on creating an HTML email template, I am venturing into the realm of developing for emails, which I know can be quite temperamental. The challenge I'm facing is in making sure that the background of my HTML email matches that of the email ...

Navigating Angular's Resolve Scope Challenges

As a junior developer, I've been diving into Angular.js and exploring the resolve feature of the route provider to preload my Project data from a service before the page loads. Previously, I was fetching the data directly inside the controller. Howeve ...

AngularJS $location Redirect Error: Property 'path' Undefined

I'm struggling with an issue in my AngularJS code where I am trying to change the URL without reloading the page when a submit button is clicked. However, I keep getting a TypeError: Cannot read property 'path' of undefined in the console. ...

Unable to supersede CSS module styling using global or external stylesheets in React, Next.js, or React Native

I'm facing a challenge finding a solution to a basic issue. I have a component that is initially styled using a class from a *.module.css file. However, I want to replace this style with one from a global stylesheet or another stylesheet but I can&apo ...

"Utilize Ajax to dynamically generate options in a dropdown menu with multiple

I am having trouble populating my multiple dropdown list using AJAX. The dropdown list is dependent on another single selection dropdown list. Here is the HTML code: <div class="form-group"> <label for="InputGender">Select Course</ ...

using percentage and float to enforce overflow-x

I have a small structure of list items inside a container and I am trying to display horizontal overflow instead of vertical overflow. However, I am having trouble achieving this, possibly due to the properties like float and percentage that I am using. I ...

Eliminate incorrect or invalid state when resetting a dropdown in an Angular ng-select component

I have integrated the ng-select plugin into my Angular project for handling dropdowns. One specific requirement I have is to reset the second dropdown when the first dropdown is changed. Below is a snippet of the code: <ng-select [items]="branchMo ...

Issues with Angular preventing app from launching successfully

So I've been working on a Cordova app with AngularJS and everything seems to be running smoothly in Chrome and other browsers. However, when I try to install the apk on Android, AngularJS doesn't seem to execute the index.html upon launch. What& ...

How to customize a disabled paper-input element in Polymer 1.0?

Help with Polymer 1.0: I've encountered an issue where setting a paper-input element to 'disabled' results in very light gray text and underline, making it hard to read. I've been trying to use CSS to change the text color but haven&ap ...

Using jQuery to show and hide elements on a webpage

One issue I'm facing is changing the content on a page depending on the clicked link. The problem arises when the displayed content for one link persists even after clicking another link, despite setting it to not display when another link is clicked. ...

Error in Typescript: The type 'Element' does not have a property named 'contains'

Hey there, I'm currently listening for a focus event on an HTML dialog and attempting to validate if the currently focused element is part of my "dialog" class. Check out the code snippet below: $(document).ready(() => { document.addEventListe ...

Guide on how to bundle a TypeScript project into a single JavaScript file for smooth browser integration

I am currently working on a small project that requires me to write a JavaScript SDK. My initial plan was to create a TypeScript project and compile it into a single JavaScript file, allowing users of my SDK to easily inject that file into their web pages. ...

ReactJS component state fails to update accurately

Let's say I have a component named Test import {useEffect, useState} from "react"; const Test = (props) => { const [Amount, setAmount] = useState(1); useEffect(()=>{ if(props.defaultAmount){ setAmount(prop ...

Steps for setting the data-url attribute in a Jquery Mobile page

Encountering an unusual issue while attempting to manually set the data-url attribute on a page during a transition from one page to another. The goal is to assign the page's data-url attribute to the URL pathname by using the following code: page. ...

Making an ajax request using JQTouch

I have implemented a toggle switch in jQTouch. I'm trying to dynamically set the position of the switch based on the result of an AJAX call. I am using jQuery as shown below, but it doesn't seem to be working. var request = $.ajax({ url ...