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

What causes the issue of undefined destructured environment variables in Next.js?

Within my application built with Next.js, I have configured a .env file containing a variable labeled API_KEY. When attempting to destructure the value of this variable, I am consistently met with undefined, as shown below: const { API_KEY } = process.env ...

Leverage Jquery within the div element to manipulate the data retrieved from a post ajax request

On my one.jsp page, I have the following post code: $.post("<%=request.getContextPath()%>/two.jsp", { vaedre: fullDate} ,function(result){ $("#theresult").append(result); }); This code generates the followi ...

Unable to retrieve Angular Service variable from Controller

I am facing an issue with my Angular Service. I have set up two controllers and one service. The first controller fetches data through an AJAX call and stores it in the service. Then, the second controller tries to access this data from the service. While ...

JavaScript error: Cannot read property 'str' of undefined

I'm attempting to retrieve specific values from a JSON array object, but I encounter an error message. var i = 0; while (i < n) { $.get("counter.html").done(function (data2) { var $html = $("<div>").html(data2); var str = ...

Navigating to a new URL using window.location.href will seamlessly embed the new page within

I am new to JavaScript and I am facing an issue with my AJAX function. The function is supposed to navigate to a new URL, but instead of loading the new page separately as if the user had typed the URL, it gets inserted inside the same div where the button ...

Can you please tell me the font size specified as 20px/26px?

Recently stumbled upon the 20px/26px value in a codebase I'm currently working on. Wondering if anyone has encountered this before and knows what its purpose is. Interestingly, it renders with the latter pixel value (26px) in Chrome. #action { font: ...

Unleashing the power of conditional exports in package.json

Within my package.json, I define an exports section: "exports": { "import": "./dist/a.es.js", "require": "./dist/b.umd.js" }, However, during development, I wish to use different pa ...

How come the method $.when().pipe().then() is functioning properly while $.when().then().then() is not working as expected

I'm still grappling with the concept of using JQuery's Deferred objects, and am faced with a puzzling issue. In this code snippet, my attempt to chain deferred.then() was unsuccessful as all three functions executed simultaneously. It wasn't ...

Determining the navigation changes within a React browser

Hi there, I'm using browserHistory.goForward() and browserHistory.goBack() to navigate forward and backward in my app with arrow buttons. However, I need a way to determine if the route has actually changed after executing browserHistory.goForward/goB ...

Changing the 'checked' attribute does not have any impact on how it appears in the browser

I am working on a button group where each button should light up when it is selected. The functionality is not fully working as expected; only one button should be active at a time. https://i.sstatic.net/oB9XG.png let stanceBar = ["long", "short", "out", ...

Postpone the appearance of a pop-up message, make it show up only once

Is it feasible to create a pop up that appears after 4 seconds and stays visible until the user interacts with the mouse? The pop up should not appear if the user scrolls before it shows. You can refer to the image for more details on the pop up box :) &l ...

What could be the reason for my component not getting the asynchronous data?

Currently, I am delving into the intricacies of React and have been following a tutorial that covers creating components, passing props, setting state, and querying an API using useEffect(). Feeling confident in my understanding up to this point, I decided ...

When using <body onload=foo()>, the function foo will not be executed

Having trouble with this code - it seems like initialize() is not being called. Check out the code here Any insight into why this might be happening? ...

Is it possible for Angular to perform bidirectional data binding in reverse between two input fields?

I'm struggling to get my two input fields to update values when the opposite input is changed. My goal is to create a simple $dollar to Gold oz calculator with two input fields. You can see a sample preview here: http://embed.plnkr.co/dw6xL95zRqJC1p ...

"The onkeydown event dynamically not triggering for children elements within a parent element that is contentEditable

Can anyone offer some insights into why this code isn't functioning as expected? My goal is to attach the listener to the children elements instead of the body so that I can later disable specific keystrokes, such as the return key. <!DOCTYPE html ...

Text area featuring unique border design, with border color change upon focus?

Currently, I have a text area with borders that are designed in a unique way. However, I am looking to change the border color when the user focuses on the text area. Do you have any suggestions on how I can achieve this effect without affecting the curre ...

What is the best way to upload this file in VueJS?

I've come across a file written in outdated syntax that I need to use in a VueJS Component. You can find the file here. For instance, consider these snippets from the file: var CCC = CCC || {}; CCC.STATIC = CCC.STATIC || {}; CCC.STATIC.TYPE = { & ...

Using Vue.js to update the v-bind:style when the mouse hovers over the element

I am working with a span element that displays different background images based on certain conditions. Here is the HTML: <span v-if="type" :style="styles" > </span> In the computed properties section: ...

Using a numeral within a Font Awesome icon symbol to customize a label for a Google Maps marker

I have a Google Maps marker displayed below, applying a Font Awesome icon as the label/icon. However, I am unsure how to a.) change the color of the marker and b.) include a number inside the marker. Referencing this Stack Overflow post This is the code ...

Designing a sleek border for form input fields

Seeking assistance in finding a solution as my extensive online search has been unsuccessful. Currently, I have this code to style my form labels: label { display:inline-block; height: 15px; width: 350px; float: left; padding: 5px; ...