Exploring the Difference Between :nth-child(even|odd) and :nth-child(int) CSS Selectors

Encountering a challenge with the CSS :nth-child pseudo selector and suspecting that something crucial has been overlooked.

index.html

<html>
<head>...</head>

    <body>

        <div class='selector'>first</div>
        <div class='selector'>second</div>
        <div class='selector'>third</div>
        <div class='selector'>fourth</div>
        <div class='selector'>fifth</div>

    </body>

</html>

style_does_not_work.css (does not work)

.selector { background-color: #ffffff; }
.selector:nth-child(1) { background-color: #f00000; }
.selector:nth-child(2) { background-color: #ff0000; }
.selector:nth-child(3) { background-color: #fff000; }
.selector:nth-child(4) { background-color: #ffff00; }
.selector:nth-child(5) { background-color: #fffff0; }

style_that_works.css (for the proof of the selector concept)

.selector { background-color: #ffffff; }
.selector:nth-child(even) { background-color: #f00000; }
.selector:nth-child(odd) { background-color: #ff0000; }

A sense of confusion arises from the disparity between the failure of :nth-child(2) and the success of :nth-child(even). Is there a specific factor causing this discrepancy?

The primary objective is to assign fixed positioned elements a variable offset from the top during dynamic injection and removal via JavaScript.

Update / Additional

Regrettably, an error can be identified in the example above. Despite resolving this issue, the underlying problem persists - even after observing functional JS-Fiddles (a source of considerable bewilderment).

Furthermore, screenshots illustrating the current dilemma have been shared:

CSS:

.notification-area {
    position: fixed;
    z-index: 999;
    width: 500px;
    height: 100%;
    overflow: hidden;
}

.notification-area.top-right {
    top: 25px;
    right: 25px;
    left: auto;

    -webkit-transition: margin 0.4s, top 0.4s, left 0.4s, right 0.4s, bottom 0.4s;
    -moz-transition: margin 0.4s, top 0.4s, left 0.4s, right 0.4s, bottom 0.4s;
    -ms-transition: margin 0.4s, top 0.4s, left 0.4s, right 0.4s, bottom 0.4s;
    -o-transition: margin 0.4s, top 0.4s, left 0.4s, right 0.4s, bottom 0.4s;
    transition: margin 0.4s, top 0.4s, left 0.4s, right 0.4s, bottom 0.4s;

}

/* these lines are completely ignored */

.notification-area:nth-child(2) { margin: 125px 0px 0px 0px; }
.notification-area:nth-child(3) { margin: 250px 0px 0px 0px; }
.notification-area:nth-child(4) { margin: 375px 0px 0px 0px; }
.notification-area:nth-child(5) { margin: 500px 0px 0px 0px; }


/* this line grabs instead - I don't want to use "even", but it shows me, that the selector :nth-child() should be fine... */
.notification-area:nth-child(even) { margin: 125px 0px 0px 0px; }

Answer №1

The second .selector is missing a closing div. Here's the correct version:

fiddle

Answer №2

The closing div tag was overlooked in the second div section.

Answer №3

For a different approach, consider using :nth-child(n+1) instead of :nth-child(2)

Answer №4

Consider replacing nth-child(n) with nth-of-type(n) as we are focusing on specific types, not just child nodes. I previously removed this response thinking the issue was an unclosed div tag, but since it persists, I am reposting it.

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

How can I use jQuery to activate and deactivate a class in HTML?

My jQuery function for handling tabs is as follows: jQuery(document).ready(function($) { tab = $('.tabs h3 a'); tab.on('click', function(event) { event.preventDefault(); tab.removeClass('active'); ...

What is the best way to design a shape (a quadrilateral with rounded edges) using CSS?

Struggling with creating a widget in React Js that has an image as the background? The image is designed to be dynamic, changing color and size based on the device. I've attempted using inline SVG and SVG within an img tag but can't seem to contr ...

The menu will showcase all currently active sub-category items whenever an item below is selected (using Joomla/Mosets Tree)

I am currently managing a Joomla website that utilizes Mosets Tree for a business directory. One issue I have noticed is that on the right side of the site, all the categories are listed. When you expand sub-categories and then roll over to another menu it ...

What is the best way to calculate precise pixel dimensions for mobile devices?

Upon inspecting the browser's developer tool, it indicates that the resolution of an iPhone X is 375*812, although this may not be the actual resolution. While CSS pixels do not always align perfectly with display resolution, the question remains - If ...

Using JavaScript to animate a background composed of SVG shapes

My code is successfully adding an svg background with js and rotating it using set interval. It works perfectly on Chrome, but not on any other browser. Any suggestions on how to make it work universally? let i = 0; setInterval(() => { document.b ...

To modify the color of text in a mat-list-option item

Using the mat-selection-list component, I have set up a list of contacts displayed through mat-list-option: https://i.sstatic.net/ri4lP.png Currently, the background-color changes when I click on a specific contact-name (e.g. Graeme Swan), and it remains ...

Learning how to track mouse wheel scrolling using jQuery

Is there a way to track mouse scrolling using jquery or javascript? I want the initial value to be 0 and increment by 1 when scrolling down and decrement by 1 when scrolling up. The value should always be positive. For example, if I scroll down twice, the ...

Is there a way to use jquery and ajax to swap out an image on a webpage when a button is clicked?

I am trying to create a button on my HTML page that, when clicked, will asynchronously change a specific image on the page. Here's what I have so far: <a href="/test/page"> button </a> What I want is for the button click to change this i ...

Extract data from nested divs using Excel VBA

Can anyone help me extract the start date from the code below? My current code does not seem to recognize the 'nested' div "daysTips." Any assistance would be highly appreciated. Thank you! HTML Screen Capture: https://i.sstatic.net/4fej8.jpg S ...

Adding or Deleting Rows from Input Table

I'm in the process of creating a website that features an input table allowing users to easily add or remove rows at their discretion. The desired UI is shown below: https://i.sstatic.net/EFAlM.jpg Here is the HTML code I have developed so far: & ...

Hovering over graphics for automatic scrolling

I have successfully implemented a hover effect that scrolls down an image inside a div. However, I am facing an issue with making the scroll longer for images of varying lengths by using calc inside the transition property. Below is the code snippet that ...

Tips for automatically closing submenus in a dropdown menu using Bootstrap 4

I am trying to figure out how to make sure that when I close my dropdown menu, the submenu within it also closes. Currently, the submenu remains open if I toggle the dropdown menu again. Visit this link for reference Here is the HTML code snippet: & ...

Using Python and Selenium to interact with an image button element by clicking on it

I've been attempting to click on that button, but no matter what I try, I can't seem to make it work. button id = edita_customer Here is the HTML code snippet: <div class="card mb-3" style="color: #ace;"> <div c ...

Tips for designing a doodle logo that includes a magnifier lens effect when hovered over

I have a vision for a unique and creative logo solution that involves incorporating a magnifier glass effect. When a user hovers over a certain area of the logo, I want it to zoom in with a magnifier glass effect. I haven't been able to find much info ...

Convert HTML files to .csv format

Is there a way to export a table from an HTML page directly to a .csv file without having to use additional code? Currently, I am using the following method: private void GenerateExcelFileOnType(string filePath1, ref DataTable dt) { if ...

The importance of white space within email design utilizing table tags in HTML

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html style="opacity: 1;" xmlns="http://www.w3.org/1999/xhtml"> <head> <meta content="text/html; charset=utf-8" http-equiv ...

Determining the quantity of displays

Can we detect the number of screens in use using JavaScript or jQuery? We are working on an application that should not be displayed on multiple screens, even if the hardware allows for it. Appreciate any assistance with this matter. Thank you. ...

Panel Freeze in Both Directions for a Grid View

Don't judge, this question may sound familiar; Link to GridView freeze pane solutions How can you freeze the header on a GridView? Freezing the Header in ASP.NET GridView - Is it Possible? Freezing Columns in a GridView - How To Do It However, th ...

Tips for extracting user-provided data from a dynamic table in Python with the help of Flask and JINJA2

I have been working on a Flask application where users can interact with a table by changing a cell and having those changes immediately reflected, such as updating them in the database. Check out the screenshots below: https://i.sstatic.net/3KCVP.png htt ...

Problem with Bootstrap 5.3 navbar dropdown functionality not functioning as expected

I'm facing an issue with my code. I attempted to use both bootstrap 5.2 and 5.1, but neither seems to be working for me. I've tried opening it in both Chrome and Firefox, but the dropdown functionality is not functioning in either browser. Does a ...