Why does the second :nth-child rule have more importance over the others in my CSS code

I am seeking clarification on the implementation of :nth-child() in CSS.

Consider the following HTML structure:

<div class="parent">
  <div class="child">child</div>
  <div class="child">child</div>
  <div class="child">child</div>
  <div class="child">child</div>
  <div class="child">child</div>
  <div class="child">child</div>
  <div class="child">child</div>
  <div class="child">child</div>
  <div class="child">child</div>
  <div class="child">child</div>
</div>

And corresponding CSS code:

div.parent div.child:nth-child(3n) {
  background-color: yellow;
}

div.parent div.child:nth-child(2n) {
  background-color: white;
}

The CSS rule defined later appears to override the earlier one. Is this behavior consistent across all environments?

Here is a JSFiddle demonstrating this scenario with the CSS rules interchanged.

Answer №1

It's important to keep in mind that CSS styles will consistently cascade down (unless specified with !important flag).

Essentially, when styling every 3rd and 2nd child elements, the style of the last overlapping child (e.g., 6, 12) will always take precedence.

This behavior is consistent across all browsers.

For further information, check out:

Answer №2

The reason for this is due to the specificity of the selector.

You can refer to the definition at this link: https://www.w3.org/TR/CSS2/cascade.html

Here is an example illustrating specificities:

*             {}  /* a=0 b=0 c=0 d=0 -> specificity = 0,0,0,0 */
li            {}  /* a=0 b=0 c=0 d=1 -> specificity = 0,0,0,1 */
li:first-line {}  /* a=0 b=0 c=0 d=2 -> specificity = 0,0,0,2 */
ul li         {}  /* a=0 b=0 c=0 d=2 -> specificity = 0,0,0,2 */
ul ol+li      {}  /* a=0 b=0 c=0 d=3 -> specificity = 0,0,0,3 */
h1 + *[rel=up]{}  /* a=0 b=0 c=1 d=1 -> specificity = 0,0,1,1 */
ul ol li.red  {}  /* a=0 b=0 c=1 d=3 -> specificity = 0,0,1,3 */
li.red.level  {}  /* a=0 b=0 c=2 d=1 -> specificity = 0,0,2,1 */
#x34y         {}  /* a=0 b=1 c=0 d=0 -> specificity = 0,1,0,0 */
style=""          /* a=1 b=0 c=0 d=0 -> specificity = 1,0,0,0 */

In your situation, the specificities are equal. Therefore, the style applied will be based on the order in which they appear, with the last one taking precedence (specifically for the background-color).

It's important to note that using !important can override these rules. Thus, it's advisable to avoid unnecessary use of it for easier maintenance.

Answer №3

Except for the :matches() and :not() pseudo-classes, every other pseudo-class holds the same weight in terms of specificity as a class selector or attribute selector. Specificity does not differentiate between two :nth-child() pseudo-classes with different arguments that target the same element. The same concept is applicable to attribute selectors - an attribute selector carries the same level of specificity as a class selector or pseudo-class, even if the attribute is "id".

Therefore, the regular cascading rules are followed: when two rules with selectors of equal specificity affect an element, the latter rule takes precedence (unless marked with !important).

Answer №4

When it comes to CSS, the last rule takes precedence over others with the same properties. This is a general principle that applies universally, not just in this particular case.

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

Tags for classes are not appearing or being activated on my website

I recently purchased a template from casethemes () and I am experiencing an issue. Despite using the same tags as their demo site, the classes are not being executed properly and appear broken on my website. Could it be that I am missing some necessary lib ...

Analyzing data visualization within CSS styling

I have the desire to create something similar to this, but I am unsure of where to start. Although I have a concept in mind, I am struggling to make it functional and visually appealing. <div id="data"> <div id="men" class="shape"></di ...

Tips for adjusting the font size on the Google Maps mapType controller

Is it possible to adjust the font size of a Google Maps mapType controller using HTML or CSS? I've managed to change the size of the controller, but struggling with the font size. https://i.sstatic.net/1n9oU.png HTML: <div #map id="map" style=" ...

Tips for accurately aligning a relative p tag within a td

Description: I am trying to prevent text overflow in a table cell and position the text underneath a header without wrapping it under an image. I have tried setting a static width for the image and adjusting the left property, but it is not working as expe ...

What is causing the Bootstrap accordion to not display content when clicked on?

As a beginner in web development, I am currently working on my very first website. One issue I'm facing is with incorporating an accordion-style card in my webpage. Although it allows me to click on different titles, the collapsed ones fail to expand ...

What steps should I take to incorporate Google sign-in on my website and gather user information efficiently?

I am looking to add the Google sign-in button to my website. While I am knowledgeable in HTML, PHP and JavaScript are not my strong suits. My goal is to allow users to sign in with their Google account and securely store their information on my database th ...

How come inactive links are still able to be clicked on?

I have been experimenting with various methods to disable links, but I seem to be unable to prevent them from being clickable. While I was successful in changing the cursor to 'not-allowed' when hovering over the disabled link, it still remains c ...

Ensuring proper input with JavaScript form validation

Currently, I am working on implementing a basic form validation feature, but it is not functioning as intended. The desired behavior is for the field border to change color to green or red based on its validity, while displaying text indicating whether t ...

Tips for resolving resizable columns in Bootstrap

Is there a way to prevent the vote button and text from extending beyond the boundaries of the div? Also, how can I specify a width value for the column when it adjusts to fit the content? Here is the code snippet: <div class="container-fluid"> ...

Struggling to grasp the concept of DOM Event Listeners

Hello, I have a question regarding some JavaScript code that I am struggling with. function login() { var lgin = document.getElementById("logIn"); lgin.style.display = "block"; lgin.style.position = "fixed"; lgin.style.width = "100%"; ...

Ways to adjust the font size in the title using HTML

Looking to adjust the text size within an h4 title. Hoping to make some letters smaller than others while keeping all in capital form. Any assistance is greatly appreciated. Thank you! ...

What is the most effective way to loop through an object containing DOM selectors as values, and subsequently utilize them to assign new values?

I have a function that takes an object retrieved from a database as its argument. My goal is to display the values of this object in a form by associating each value with a specific DOM selector. Here is the code snippet where I achieve this: function pai ...

How to pass extra value in IE7 and IE8 when selecting an option from a 'select' form

When passing expiry parameters using a form 'select' option, everything seems to be working fine in most browsers except for IE7 and IE8. Upon inspecting the form snippet and the array received from the card processor logs, it was noticed that an ...

Displaying a specific fieldset based on the radio button selection

I have created a form to handle user input using PHP, with the initial question prompting the user to choose from three radio buttons for the "type" parameter - the options being "book", "journal", and "website". Here is what the code looks like: <stro ...

Using the HTML <span> and svg elements together does not allow them to be inline with each other

In my current scenario, I have a fieldset that is inline with another one on the page. The specific fieldset in question contains an SVG circle and some text. My objective is to have both elements inline with each other, while allowing the fieldset to adj ...

Using an HTML img tag without success, despite having the correct link

My HTML img tags are not working even though the link is correct. I have been attempting to resolve this issue for quite some time by researching multiple websites and trying various solutions, but unfortunately, nothing seems to be working. All I want i ...

Bootstrap 4 collapsible navbar with a stacked design

I am struggling to create a collapsible navbar. Even though everything seems to be working, the nav items are not stacking vertically as they should be. Instead, they are appearing horizontally next to each other. Here is the code snippet: <nav class= ...

What is the best way to widen each tab so they fill up the entire width of the content block?

As a newcomer to both programming and this website, I've been exploring various codes for creating vertical and horizontal tabs. I have a specific query about this particular example found at https://jsfiddle.net/eu81273/812ehkyf/: My goal is to adju ...

AngularJS: Utilizing bold text to enhance the separation of concerns between controllers and templates

In my AngularJS version 1 application with Ecmascript 6, I have a requirement to display a string where one part is in normal weight and the other part is bold. For instance, consider the following scenarios: Will start now Will start in 6 minutes Will ...

How can I customize a default button in HTML to hide the selected option from the dropdown menu?

Hey there! I'm currently working on a website that needs to be bilingual, with Spanish as the default language. I want to include a dropdown button that allows users to translate the content into English. Here's what I've tried so far: ...