Style the nth child of a particular type in CSS with a unique color scheme

Is there a way to select the nth child of type and apply different colors without assigning IDs because they are dynamically generated in a loop from a template engine?

I found some useful information on this topic here:

https://www.w3schools.com/cssref/sel_first-of-type.asp

https://www.w3schools.com/cssref/sel_nth-of-type.asp

https://www.w3schools.com/cssref/sel_last-of-type.asp

After implementing the code snippet below, I noticed that all headers have the same color. Can anyone explain why they don't have different colors as expected?

#service {
  background: #000000;
  color: #ffffff;
  border-bottom: 1px solid #424242;
}
#serviceItems {
  display: flex;
  margin: 0 50px;
}
.serviceItem {
  flex: 1;
  text-align: center;
  margin-top: 0;
}
.serviceItemHeader:first-of-type {
  color: #80E000;
}
.serviceItemHeader:nth-of-type(2) {
  color: #F97A00;
}
.serviceItemHeader:nth-of-type(3) {
  color: #B277DD;
}
.serviceItemHeader:last-of-type {
  color: #e2c100;
}
<div id="service" class="section">
  <div id="serviceItems">
    <div class="serviceItem">
      <h4 class="serviceItemHeader">Container 1</h4>
      <h4>Container 1</h4>
    </div>
    <div class="serviceItem">
      <h4 class="serviceItemHeader">Container 2</h4>
      <h4>Container 2</h4>
    </div>
    <div class="serviceItem">
      <h4 class="serviceItemHeader">Container 3</h4>
      <h4>Container 3</h4>
    </div>
    <div class="serviceItem">
      <h4 class="serviceItemHeader">Container 4</h4>
      <h4>Container 4</h4>
    </div>
  </div>
</div>

Answer №1

Yes, this inquiry has been raised and resolved before. To address your specific issue, you should assess the .serviceItem utilizing nth-of-child and then implement the outcome to the underlying .serviceItemHeader category.

#service {
  background: #000000;
  color: #ffffff;
  border-bottom: 1px solid #424242;
}

#serviceItems {
  display: flex;
  margin: 0 50px;
}

.serviceItem {
  flex: 1;
  text-align: center;
  margin-top: 0;
}

.serviceItem:first-of-type .serviceItemHeader {
  color: #80E000;
}

.serviceItem:nth-of-type(2) .serviceItemHeader {
  color: #F97A00;
}

.serviceItem:nth-of-type(3)  .serviceItemHeader {
  color: #B277DD;
}

.serviceItem:last-of-type .serviceItemHeader {
  color: #e2c100;
}
<div id="service" class="section">
  <div id="serviceItems">

    <div class="serviceItem">
      <h4 class="serviceItemHeader">
        Container 1
      </h4>
      <h4>
        Container 1
      </h4>
    </div>

    <div class="serviceItem">
      <h4 class="serviceItemHeader">
        Container 2
      </h4>
      <h4>
        Container 2
      </h4>
    </div>

    <div class="serviceItem">
      <h4 class="serviceItemHeader">
        Container 3
      </h4>
      <h4>
        Container 3
      </h4>
    </div>

    <div class="serviceItem">
      <h4 class="serviceItemHeader">
        Container 4
      </h4>
      <h4>
        Container 4
      </h4>
    </div>

  </div>
</div>

Answer №2

One way to understand the *-of-type selectors is that they target sibling elements specifically. In your scenario, the elements you are attempting to style are actually "cousins", which is why the styling isn't being applied as expected.

To resolve this issue, apply the *-of-type selector to the parent elements first. Once the parent elements are selected, proceed with customizing the appearance of the headers within.

#service {
  background: #000000;
  color: #ffffff;
  border-bottom: 1px solid #424242;
}

#serviceItems {
  display: flex;
  margin: 0 50px;
}

.serviceItem {
  flex: 1;
  text-align: center;
  margin-top: 0;
}

.serviceItem:first-of-type .serviceItemHeader {
  color: #80E000;
}

.serviceItem:nth-of-type(2) .serviceItemHeader {
  color: #F97A00;
}

.serviceItem:nth-of-type(3) .serviceItemHeader {
  color: #B277DD;
}

.serviceItem:last-of-type .serviceItemHeader {
  color: #e2c100;
}
<div id="service" class="section">
  <div id="serviceItems">

    <div class="serviceItem">
      <h4 class="serviceItemHeader">
        Container 1
      </h4>
      <h4>
        Container 1
      </h4>
    </div>

    <div class="serviceItem">
      <h4 class="serviceItemHeader">
        Container 2
      </h4>
      <h4>
        Container 2
      </h4>
    </div>

    <div class="serviceItem">
      <h4 class="serviceItemHeader">
        Container 3
      </h4>
      <h4>
        Container 3
      </h4>
    </div>

    <div class="serviceItem">
      <h4 class="serviceItemHeader">
        Container 4
      </h4>
      <h4>
        Container 4
      </h4>
    </div>

  </div>
</div>

Answer №3

When using CSS, keep in mind that elements are counted as children of their direct parent. This means that each header within the .serviceItem parent is considered the first child. To correct this issue, you can make the following adjustments:

#service {
  background: #000000;
  color: #ffffff;
  border-bottom: 1px solid #424242;
}

#serviceItems {
  display: flex;
  margin: 0 50px;
}

.serviceItem {
  flex: 1;
  text-align: center;
  margin-top: 0;
}

.serviceItem:first-of-type .serviceItemHeader {
  color: #80E000;
}

.serviceItem:nth-of-type(2) .serviceItemHeader {
  color: #F97A00;
}

.serviceItem:nth-of-type(3) .serviceItemHeader {
  color: #B277DD;
}

.serviceItem:last-of-type .serviceItemHeader {
  color: #e2c100;
}
<div id="service" class="section">
  <div id="serviceItems">

    <div class="serviceItem">
      <h4 class="serviceItemHeader">
        Container 1
      </h4>
      <h4>
        Container 1
      </h4>
    </div>

    <div class="serviceItem">
      <h4 class="serviceItemHeader">
        Container 2
      </h4>
      <h4>
        Container 2
      </h4>
    </div>

    <div class="serviceItem">
      <h4 class="serviceItemHeader">
        Container 3
      </h4>
      <h4>
        Container 3
      </h4>
    </div>

    <div class="serviceItem">
      <h4 class="serviceItemHeader">
        Container 4
      </h4>
      <h4>
        Container 4
      </h4>
    </div>

  </div>
</div>

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

Troubleshooting problem with CSS background image

I'm looking to make my webpage more dynamic and interactive. One issue I have is that the background image of the body element stretches when new elements are added, which is not the desired behavior. Any suggestions on how I can fix this? <styl ...

The Google Language Translator disregards the formatting

Currently, I am in the midst of developing a website with Wordpress and have successfully integrated Google Language Translator. Everything seems to be working well, except for one issue - when I translate the content, it alters the font size. Prior to tra ...

Spring Boot - delivering unadulterated HTML and static materials

After spending countless hours working on this, I am still unable to figure out how to serve pure .html pages. The project I am referring to can be found at: https://github.com/robson021/Invoice-Writer Although the Thymeleaf engine works perfectly, I enco ...

Sending JavaScript variables to an external CSS file

I've been searching for a solution without much luck. I must admit, my CSS skills are pretty basic. Currently, I am using Muxy.io to manage notifications for my livestreams. The platform allows customization of notifications through HTML and CSS file ...

When opening a dialog at the bottom of the page, the window will automatically scroll to the top

I'm encountering an issue with a page that has a width exceeding 100% (2000px). Whenever I click to display a dialog from a button located at the end of the horizontal page, the window automatically scrolls back to the beginning of the page before sho ...

What are some ways to personalize the depth graph in amcharts?

I am having trouble modifying the depth graph amchart and I'm struggling to grasp how it functions and how to design it like the image below. Below is the link to the original graph that I am trying to customize: Link https://i.stack.imgur.com/nbWd ...

Issue with Flex property not being supported in Safari browser

.rq-search-container { position: relative; width: 100%; background: white; display: flex; flex-direction: row; align-items: flex-start; border-radius: 2px; z-index: 30; -webkit-flex: 1 0 15em; } While this code functi ...

Switch back and forth between adding and removing a table row using jQuery

Currently, I am developing a drop-down feature for a table that populates its data using MySQL. The functionality involves creating a new table row below the current one when a user clicks a button. However, instead of generating multiple new rows each tim ...

The material UI styled component is not appearing as expected

I'm having trouble getting the MUI styled() utility to apply styles to <MyComponent>Styled div</MyComponent> in my index.jsx file. Any ideas why? import Button from '@mui/material/Button' import Grid from '@mui/mater ...

Having trouble with JavaScript not working when clicking an image and toggling a div?

Why isn't the onclick image and toggle div functionality working with JavaScript? I made the change from: <input type="button" id="Showdiv1" name="Showdiv1" value="Show Div 1" onclick="showDiv('div1')" /> to: <img src="https://d ...

Error: The function $.simpleTicker is not defined

Every time I try to call a jQuery function, an error shows up: Uncaught TypeError: $.simpleTicker is not a function I attempted changing $ to jQuery but it didn't resolve the issue. This represents my jQuery code: (function ($) { 'use ...

Embedding PHP code within HTML causing functionality issues

I'm attempting to include PHP within CSS, but the outcome is not what I expected. Instead of displaying the desired results, it's showing me the variable names and an echo statement: <!doctype html> <?php require_once("mysqlconnect.php" ...

Using Jquery to duplicate a row from one table and insert it into another table

Recently, I've dived into the world of jQuery and JavaScript with the goal of creating a simple app. The main functionality I'm trying to implement is the ability to copy a row from one table to another and then delete the original row when a but ...

When a specific JavaScript function is triggered, the value of an HTML control will reset to its original default value

I have a form with a specific requirement. I need to allow users to input data in a text field and press enter, which should dynamically create new controls like another text field, a dropdown menu, and another text field using jQuery. While the functional ...

I am experiencing difficulties with my custom font not functioning properly

I've experimented with the following code: @font-face { font-family: Jua; src: url('/fonts/jua.ttf'); } @font-face { font-family: Jua; src: url('..../fonts/jua.ttf'); } @font-face { font-family: Jua; src: url('.../fonts/jua.t ...

Python: Convert a variable to an HTML file

This question may seem simple, but I've been searching for a solution without success for hours. I have an HTML file called "teste.html" I am using jinja 2 to make changes in my HTML. env = Environment(loader=FileSystemLoader('.')) template ...

Can dynamic CSS imports be unloaded in a React application?

I am facing an issue with loading two files using react.lazy and suspense: import React, { Suspense, lazy } from "react"; import { Route, Redirect } from 'react-router-dom'; const MainLayout = lazy(() => import('Components/Layout/MainL ...

Increase the space below the footer on the Facebook page to allow for an

I recently created a webpage at and noticed that it is adding extra height below the footer on my Facebook page: "" I am seeking assistance on how to remove this additional 21px height below all content in the footer. I have tried various templates but n ...

How can I set a minimum height for a table on my website?

Is there a way to make a table that is at least 50px in size, but can still enlarge if there is a lot of text inside? I'm not sure if this even makes sense, but any help would be appreciated. Thank you! ...

Ensure chip component (div) dynamically resizes its width to accommodate varying lengths of child text elements

I have a main container with two child elements (a text span and an image svg) created using the Material UI component library. My objective is to dynamically adjust the width of the chip based on the length of the text content inside it, while ensuring a ...