Switching the background color of alternating divs in reverse order: a step-by-step guide

I am looking to alternate the background color of divs between odd and even, with the last div being grey and the second to last div being green. I have tried using the odd/even classes in CSS, but it did not work as expected.

.main{
width:500px;
height: 500px;
border:1px solid blue;
}
.box{
width:300px;
height: 100px;
border:1px solid red;
}

.box:nth-child(odd) {
  background: grey;
}

.box:nth-child(even) {
  background:green;
}
<div class="main">
<div class="box">1</div>
<div class="box">2</div>
<div class="box">3</div>
<div class="box">4</div>


</div>

I could use some guidance on achieving my desired color scheme for the divs. Any help would be appreciated. Thank you.

Answer №1

To address your query, you can utilize the nth-last-child CSS selector, which can help resolve your specific requirement. I have made some adjustments below that should assist with the issue. For further information on nth-last-child, refer to this link: https://www.w3schools.com/cssref/sel_nth-last-child.asp

Thank you.

.main{
width:500px;
height: 500px;
border:1px solid blue;
}
.box{
width:300px;
height: 100px;
border:1px solid red;
}

.box:nth-child(odd) {
  background: grey;
}

.box:nth-child(even) {
  background:green;
}

.box:nth-child(odd) {
  background: grey;
}

.box:nth-last-child(2) {
  background:green;
}

.box:nth-last-child(1) {
  background:grey;
}
<div class="main">
<div class="box">1</div>
<div class="box">2</div>
<div class="box">3</div>
<div class="box">4</div>


</div>

Answer №2

.main{
width:500px;
height: 500px;
border:1px solid blue;
}
.box{
width:300px;
height: 100px;
border:1px solid red;
}

.box:nth-child(odd) {
  background: grey;
}

.box:nth-child(even) {
  background:green;
}

.box:last-child {
  background: grey;
}
.box:nth-last-child(2){
  background:green;
}

 
<div class="main">
<div class="box">1</div>
<div class="box">2</div>
<div class="box">3</div>
<div class="box">4</div>
<div class="box">5</div>
<div class="box">6</div>
<div class="box">7</div>


</div>

Answer №3

To target elements from the last row, you can utilize the :nth-last-child() selector.

.main{
  width:500px;
  height: 500px;
  border:1px solid blue;
}
.box{
  width:300px;
  height: 100px;
  border:1px solid red;
}

.box:nth-last-child(odd) {
  background: grey;
}

.box:nth-last-child(even) {
  background:green;
}
<div class="main">
<div class="box">1</div>
<div class="box">2</div>
<div class="box">3</div>
<div class="box">4</div>
</div>

Answer №4

To target a specific div element, you can utilize the nth-last-child selector. Feel free to test out my example below:

.container {
  width: 600px;
  height: 600px;
  border: 2px solid black;
}

.item {
  width: 300px;
  height: 50px;
  border: 1px solid blue;
}

.item:nth-last-child(3n+1) {
  background: yellow;
}

.item:nth-last-child(3n+2) {
  background: purple;
}
<div class="container">
  <div class="item">A</div>
  <div class="item">B</div>
  <div class="item">C</div>
  <div class="item">D</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

Tips for dynamically filling HTML content with Ajax calls

I'm currently in the process of creating a website for my semester project, and I need to dynamically populate HTML content from an AJAX response. The data I'm receiving is related to posts from a database, but I specifically need to display 5 jo ...

Disable the javascript link on small devices

I currently have a javascript link (Trustwave) on my desktop website theme that I need to deactivate when viewed on mobile devices: Located in footer.tpl: <div style="position:absolute; margin-left:100px; margin-top:50px"> <script type="text/j ...

Updating file extension name in ReactJS: A quick guide

Looking to modify a file name and extension within the react.js public folder. Changing index.html to index.php https://i.stack.imgur.com/zp1Ga.jpg ** ...

The function client.guilds.find cannot be located

Hey there! I've been tasked with working on a Discord bot that requires several dependencies to function properly. I've installed the necessary dependencies and attempted to run the bot using 'forever -o out.log bot.js'. However, I enc ...

Tips on creating a React Vite Typescript website that utilizes the entire height and ensures a minimum width

I'm currently working on building a portfolio webpage with React, Vite, and Typescript, but I'm facing an issue where the content is not taking up the full height of the page. I have multiple pages with different lengths of content that I want to ...

Discover the method for tracking idle time with jQuery and PHP

I have a script that utilizes PHP sessions through a custom class. One of the methods in this class calculates the remaining seconds before the session expires. Whenever the user refreshes the page or opens a new one, the idle time counter is reset using ...

Activating a function that requires locating a dynamically loaded element on the webpage using AJAX

I have a unique page on my website that allows users to make edits. Whenever they click on an item, the edit form is seamlessly loaded into a specialized section of the page using AJAX. Depending on the chosen item, the form fields are already prefilled w ...

CSS Float issue on resizing: avoid element displacement due to margin or padding (responsive layout)

Having an issue that I need help with: My header includes a menu, news sliding with flexslider, and a search input: The problem occurs when I resize the browser manually or reload it with a smaller width; the right element jumps down, causing a pushdown ...

Stop users from saving the page in Next.js

I'm currently working on a NextJs project that involves building an editor application. I want to ensure that the editor functionality does not work when users attempt to save the page in a different format, similar to how applications like Youtube an ...

The click event for getelementbyid() function is malfunctioning

I need assistance with a website I am creating that plays audio when a certain condition is met. Specifically, I want the audio to play if x falls within a specific range of numbers, but also continue playing if x does not fall within that range after th ...

Exploring the font variables in the asset pipeline of Rails 7

Creating a habit of defining a set of root variables is crucial for maintaining consistency throughout an application. :root { --main-font-family: "Helvetica Neue", Helvetica, Roboto, Arial, sans-serif; --kbd-font-family: Consolas, "Libe ...

What is the best way to simulate global variables that are declared in a separate file?

dataConfiguration.js var userData = { URIs: { APIURI: "C" }, EncryptedToken: "D" }; configSetup.js config.set({ basePath: '', files:['dataConfiguration.js' ], ..... UserComponentDetails: .....some i ...

What could be causing this code to fail in making changes to the HTML document?

I tried incorporating the following code into my website: $('.feed-item').append('<p> This is paragraph element. </p>'); You can view it on this page: Test Unfortunately, the code does not seem to be functioning properly. ...

What is the proper way to utilize the src attribute for connecting HTML code?

I've noticed that in HTML you can include scripts like this: <script src="myscripts.js"></script> But I was wondering, is it possible to link an entire HTML page? Something like this: <html src="testing.html">< ...

What is the best way to style HTML strings in C#?

Wondering how to create HTML helpers in ASP.net? Looking for the simplest way to generate HTML strings or templates without having to change all double quotes to single quotes manually? You can streamline your process by using a syntax similar to ES6 templ ...

Uncovering the array within Javascript

I'm struggling to figure out why I can't access an array that PHP sends back to me. When AJAX makes a call, I send back this: $response['success'] = true; In my PHP file, I use echo json_encode($response); to send it. However, when I ...

What is the best way to modify the values in an initialized array once the fetchData method has been executed?

As a beginner in Vue.js, I am currently working on a project that involves updating initialized arrays in the data() section of my component using the fetchData method. Below is a simplified version of the code: <script> import axios from 'axi ...

Fixing inconsistent font sizes across various browsers

During the development of my website, I couldn't help but notice a significant variance in font sizes between Internet Explorer and other browsers. Here's an example of what my page looks like: I intended for it to resemble the first and second ...

Utilizing the json_encode() function in PHP and JSON.parse() method in JavaScript for handling file data interchange

Utilizing json_encode() in PHP to store an array in a file, then leveraging JSON.parse() in JavaScript on the client side to read the json encoded file and pass it as an array to a sorting algorithm: The result of my json_encode() operation in the ...

Encountering an undefined property error while trying to access index '0' in Angular 6 with Angular Material's mat-radio-group component, specifically when attempting to set a dynamic variable within

Currently, I am working with Angular 6 and Angular Material. My project involves a dynamic list of polls with various options. I am attempting to display the selected option using two-way data binding. However, due to the dynamic nature of my list, I have ...