What is the best way to choose alternate div class elements using only CSS without any javascript?

While I have experience using javascript and php to achieve a certain effect, I am now curious about the possibility of achieving the same effect solely with css.

In my current project, I have a container that houses multiple items. Each item consists of an image followed by a description in a div element. My goal is to have the background color of the description alternate for every other item.

Is it feasible to accomplish this using only css? If so, how can it be done? I have made attempts using selectors such as:

.item:nth-child(odd){background-color:red}
.item .description:nth-of-type(odd){background-color:orange;}

However, I have not been successful in getting it to work. Any tips, suggestions, or comments would be greatly appreciated.
Below is a simplified version of the sample code illustrating what I am working on.

<style>
#container{width:100% height:100%;}
.item {float:left; width:250px; height:700px;}
.item img {width:250px; height:250px; float:left;}
.description {width:250px; height:450px; float:left; background-color:blue;}
.description:nth-of-type(even){background-color:red;}      // <- This is the line causing issues!!
</style>

<html>
 <body>
  <div id="container">
   <div class="item">       //Item 1
    <img src="image.jpg"/>
    <div class="description"> //I want this (and every odd number) to be blue 
     <h1>Title</h1>
     <h2>Sub Title</h2>
     <p>Lorem Ipsum dolor sit for Adun!</p>
     <a href="#">::LEARN MORE::</a>
    </div>
   </div>
   <div class="item">      //Item 2 and beyond...
    <img src="image.jpg"/>
    <div class="description"> //And I want this (and every even number, red)
     <h1>Title</h1>
     <h2>Sub Title</h2>
     <p>Lorem Ipsum dolor sit for Adun!</p>
     <a href="#">::LEARN MORE::</a>
    </div>
   </div>
  </div>
 <body>
</html>

Answer №1

If you're looking to target odd child elements of the class called "item," then consider using the nth-child() selector.

.item:nth-child(odd) .description {
    background-color: red;
}

Check out a demonstration here: http://jsfiddle.net/ThinkingStiff/j9S8v/

Answer №3

If we utilize the following CSS snippet, it may be achievable:

.item:nth-of-type(odd)  .description{background-color:orange;}  

Alternatively, you could also try:

.item:nth-child(odd) .description{background-color:orange;}

Feel free to check out my screenshots for reference:
I trust this will assist you in achieving your goal.

Answer №4

To style every other .item element, use nth-of-type selector:

#container{width:100% height:100%;}
.item {float:left; width:250px; height:700px;}
.item img {width:250px; height:250px; float:left;}
.description {width:250px; height:450px; float:left; background-color:blue;}
.item:nth-of-type(even) .description {background-color:red;} 

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

Displaying a trio of items in a horizontal row on the page

I am currently working on displaying a list item with three data elements positioned next to each other. My goal is to achieve the following layout: https://i.sstatic.net/XiFzE.png However, at the moment, my list appears like this with the circle distort ...

What is the process for sending a single post to two separate actions?

I am working with HTML and Javascript code to send a form using method=post to an action="www.randomaction.com/randomaction.php". My goal is to also send the form data to my email (the same post), but without opening the user's mail client. Instead, ...

Is it window.jQuery or just jQuery?

(function($) { // plugin code })(window.jQuery); It appears that this code produces almost the same effect as: (function($) { // plugin code })(jQuery); Is it necessary to use window.jQuery instead of just jQuery as the function argument? Does it serve ...

Tips for displaying an image that is embedded within a CSS file

I discovered an interesting background image embedded in a CSS file. Is there a way for me to actually view it? "iVBOR..." to "5CYII=" and saved it in a file named image.png - unfortunately, this method did not yield the desired outcome.</p> ...

Keep the Bootstrap dropdown menu open when the search bar is in focus

I am working on a customized bootstrap dropdown menu that needs to remain open when the search bar within the Events dropdown is focused. I have managed to make it open and close on hover, but now I need it to stay open under certain conditions. Below is ...

Setting a parent for CSS selectors in Material UI: A step-by-step guide

Currently, I am in the process of developing a Chrome Extension that incorporates Material UI. By using the inject method, the extension is able to apply all of the Material UI styles seamlessly. I have been contemplating the idea of adding a parent selec ...

The alignment of rows and columns is not proper

I have been using bootstrap and encountering an issue with aligning rows containing 2 columns each. The alignment is not appearing as desired. What I want: https://i.sstatic.net/OoIiB.jpg However, what I am getting is different: https://i.sstatic.net/FpI3 ...

Remove the icon disc background from a select element using jQuery Mobile

As I delve into building my first jQuery Mobile app using PhoneGap/Cordova, I have encountered some challenges along the way in getting the styling just right, but overall, things are going well. However, when it comes to working with forms, I hit a roadb ...

Exploring the power of nested styled components in Material UI is a great way to elevate the styling of your project

Can someone explain how to access a second styled component using '@mui/system' in order to add a hover effect to a parent element that will modify the max-height of its child? Please keep in mind that I am referring to mui's styled compone ...

Struggling to fix the excess white space appearing underneath my website

I am new to HTML/CSS and I'm currently working on adding a timeline to my website. However, I've encountered a strange issue with the #timeline class where there is an odd block of space below it whenever I try to adjust the height. So far, I ha ...

Tips for extracting website language using Selenium in Python

When configuring the language in Selenium, I use: chrome_options.addargument("--lang=en"). During testing, I must verify that the language is indeed set to English. Perhaps I can confirm this by checking the value inside <html lang='... ...

Using the display property of inline-block in conjunction with PHP will lead to unexpected results (see screenshots provided)

I am in the process of developing an online store using PHP/SQL to showcase product information. I have applied a display: inline-block in the CSS, and it functions properly without PHP. However, when PHP is added, it seems to switch to a display: block e ...

What is the best way to create text boxes that can expand and collapse within a UIWebView?

I am looking to present text in a UIWebView with expandable or collapsible boxes that contain titles. The user should be able to tap the bar of a collapsed box to expand it. Is there a simple solution available that can be easily integrated into a local ...

JavaScript - Relocating the DIV Scrollbar to the Top Upon iFrame SRC Modification

re: I have created a user-friendly website for comparing different potential "expat" cities. Each city has links (target=iframe) for cost of living data, Wikipedia, expat blogs, climate information, and Google Maps. In the left column, there are control ...

Struggling to figure out how to make this Vue function work

I am working with a list of tasks, where each task is contained within a div element. I am looking to create a function that changes the border color of a task to red when clicked, and reverts the previous task's border to normal. I have two files: &a ...

Different sized image grid display

Could you please take a look at this screenshot: I am facing an issue with the grid layout. The first image in the grid is too short, which results in a big gap between the upper left and lower left pictures. Here is what it looks like currently: Is ther ...

HTML Crossword Puzzles

This intriguing puzzle exclusively allows lowercase letters. How can I modify it to accept both upper and lowercase letters? Alternatively, is there a way to prompt the user to disable caps lock? HTML <body onload="initializeScreen()"> ...

PHP & HTML version of clang-format alternative

I have come across clang-format which is primarily used for c/c++/obj-c code formatting. Can you suggest a similar tool that can automatically format/reformat PHP/HTML code to maintain consistency? What would be your recommendation and why? We are looking ...

What is the best way to change the text within the first tag of an HTML markup using either jQuery or basic JavaScript?

My task involves dealing with an array of markup strings, similar to: const items = [ '<p class="item">text</p>', '<h1>hello</h1>', ]; I am looking for a way to replace the text content within the ...

Tips for saving and editing a file with JavaScript

I need a website visitor to input text into a text area on my site. When they submit the form, I want the entered text to be saved in a .txt file located in the same directory as the current web page. I am unsure of how this can be accomplished, and if i ...