Adjust the background color of alternate elements

I am looking to customize the background colors of every other element within the structure provided below:

<div class="dets">
 <div>Simple Layout</div>
 <div>Few Pictures/Links</div>
 <div>Element Uniformity</div>
</div>

Specifically, I aim to have the first [Simple Layout] element displayed with a white background, the second [Few Pictures/Links] element with a black background, and so forth. This pattern should be applied to all instances of the "dets" class, without counting previous elements. I prefer not to utilize a table for this purpose.

Currently, I am utilizing the following jQuery code to achieve this background-color customization:

$(".dets div:odd").css('background-color', 'white');
$(".dets div:even").css('background-color', 'black');

Answer №1

Give this a shot:

$(".details>div:nth-child(odd)").css('background-color', 'white');
$(".details>div:nth-child(even)").css('background-color', 'black');

You can achieve the same result using only CSS:

.details>div:nth-child(odd){
 background-color:white;
}
.details>div:nth-child(even){
 background-color:black;
}

Answer №2

Utilizing the css nth-child is recommended for better performance.

To optimize indexing time, consider using id instead of class like #dets

There are various selectors available to choose from based on your specific requirements, such as:

  • tr:nth-child(2n+1) Representing the odd rows of an HTML table.
  • tr:nth-child(odd) Representing the odd rows of an HTML table.
  • tr:nth-child(2n) Representing the even rows of an HTML table.
  • tr:nth-child(even) Representing the even rows of an HTML table.
  • span:nth-child(0n+1) Representing a span element which is the first child of its parent; equivalent to the :first-child selector.
  • span:nth-child(1) Equivalent to the above.
  • span:nth-child(-n+3) Matching if the element is one of the first three children of its parent and is also a span.

.dets>div:nth-child(even){
background:#000;
color:#fff;
}

.dets>div:nth-child(odd){
background:#fff;
}
<div class="dets">
 <div>Simple Layout</div>
 <div>Few Pictures/Links</div>
 <div>Element Uniformity</div>
</div>

Answer №3

One way to implement this effect exclusively in CSS is by:

.info div:nth-child(odd){ background-color: red; } .info div:nth-child(even){ background-color: blue; }

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

Display all the names of the files from various file inputs in a unified notification

I have developed a function that checks if the selected file names already exist in the database. It currently alerts a message for each file name found in the database, which can be overwhelming with multiple files. I am looking for suggestions on how t ...

The object you are attempting to use does not have the capability to support the property or method called 'after'

When attempting to add a div tag dynamically using javaScript, I encountered an issue with the .after function not working in IE9+. The error message "SCRIPT438:Object doesn't support property or method 'after'" appeared in the console. If a ...

Post the HTML5 player on your Facebook feed

Currently, I have a player that exists in both Flash and HTML5 versions. When calling a page through an iframe, the browser and device are detected automatically to load the player accordingly, and this setup is functioning correctly. Prior to implementin ...

Inserting Multiple Inputs

I have a unique application interface that is structured in the following manner: The rows within the application consist of either group headings (displayed as rows with single inputs) or ingredient forms (comprising a small input field, followed by a se ...

Issue with Tabulator: The top and bottom calculations do not shift position when a column is toggled. Seeking a solution to toggle a column and refresh the table without losing the current

My main objective is to toggle the visibility of toggles while maintaining consistent formatting. However, I currently face an issue where using a filter achieves this but results in losing the current scroll position of the tabulator, which is not accepta ...

JavaScript incorrectly constructs date strings

Hey there, I've been attempting to create a JavaScript date object using a string but for some reason, it's consistently off by one day. Every time I try, it ends up showing the wrong day. Below is the code snippet in question: var date = new Da ...

Link an HTML contact form to an Express.js backend server

Hey there, I'm a newcomer to web development and I've been working on creating the backend code for a contact form, but it keeps throwing errors. Here's my HTML code for the contact form: </div> <div class="row"> ...

Ensure that a specific value is maintained for a property of an element throughout its animation

There are two distinct types of components that I am working with, which I will refer to as .a and .b. It is possible that these components have been assigned certain CSS animations. I do not have the ability to control these keyframes, whether they are a ...

Iterate over a JSON document, insert an item, and then store the updated data in a separate

My JSON file contains elements like this: var data=[{ "Name": "Jeff", "Age": 35 }, { "Name": "cliff", "Age": 56 }] I need to include a new field called 'Country'. So the updated structure should be: var data=[{ "Name": "Jef ...

deciding on the axis for flipping a div with CSS

Is there a way to change the setting so that when using -webkit-transform: rotateY(180deg), it rotates from either the far left or right edge of the div, similar to how a door swings open? ...

Choosing a CSS selector for a class that does not have a specific ID

Looking for a way to select all elements with the class .tab-pane except for those with the id #home. I attempted using .tab-pane:not#home{...}, but it proved unsuccessful. Any ideas on how to achieve this? Sample HTML <div id="home" class="tab-pan ...

Tips for extending the space between one element and another when the width decreases:

Currently in the process of building a website using HTML/CSS/JS and have run into an issue. My front page features an image with text overlay, where the image has 100% width and a fixed height of 487px. I positioned the text using position:relative; and t ...

Place the Div in a consistent position on images of varying widths

I have a dilemma with my class that is supposed to display images. The issue arises when I try to place a div within an image inside this class. Everything works smoothly when the image takes up the entire width of the class, but as soon as the image widt ...

Determine whether the string includes any character during keyup event

I'm currently working on implementing a live search feature on my website. I have managed to make it work where the input field and link title match, but it only matches complete words. I am wondering if there is a way to display results that contain ...

Tips for setting one image as the background for an entire page

Take a look at the web template image linked below: URL - https://ibb.co/cD3iH8 I want to utilize the abstract design image above as the background for an entire page. Please provide guidance on the most effective way to accomplish this task. ...

Is there a way to enable hover functionality on mobile devices? I wish for the hover effect seen on desktop to be triggered automatically on mobile devices

I attempted to implement @media (hover: hover) without success. In my design, I have three images in a row that reveal a text overlay when hovered over with a mouse. However, the issue arises when I try to switch to a mobile view, as the images remain un ...

How can I determine which component the input is coming from when I have several components of the same type?

After selecting two dates and clicking submit in the daterange picker, a callback function is triggered. I have two separate daterange pickers for SIM dates and Phone dates. How can I differentiate in the callback function when the user submits dates from ...

When utilizing the JavaScript createElement() method to create elements on keydown, it will not be compatible with jQuery's draggable() method

I'm currently developing a drag and drop feature for a project, allowing users to add items to a work area and then position them by dragging. I'm facing an issue where I want to create multiple instances of the same element using a key code, but ...

Set Divs in Absolute Position Relative to Each Other

I need to create a simple navigation system using <div> elements as individual pages. The goal is to have "next" and "back" buttons that allow users to switch between these pages with a smooth fade-in and fade-out effect, all powered by jQuery. Howev ...

The JQuery function has not been defined within the scripts file

It seems like my jquery function is suddenly undefined and I can't figure out why. I made sure to call jquery before the scripts file, so that's not the issue. Strangely, the jquery was functioning properly until I placed it inside this specific ...