How is it that styling is still being applied at the top even though media queries do not impact specificity?

Using this particular design

div {
  @media (min-width: 0px) {
     color: blue;
  }
  color: red;
}
<div>
hello
</div>

I anticipate the color to appear as red. Nevertheless, it is displaying as blue and I cannot fathom why. Tested on Chrome. The color remains red in alternative browsers.

Answer №1

The reason behind this behavior is the way the nested @rule gets unwrapped:

@rule {
  & {
    /* ... */
  }
}

This concept is elaborated in this section of the specifications and even includes an illustrative example highlighting this scenario:

.foo {
  display: grid;

  @media (orientation: landscape) {
    grid-auto-flow: column;
  }
}
/* can be rewritten as
  .foo {
    display: grid;

    @media (orientation: landscape) {
      & {
        grid-auto-flow: column;
      }
    }
  }
*/

If we include the & selector in the color: red rule, it results in the same level of specificity:

div {
  @media (min-width: 0px) {
     color: blue;
  }
  & { color: red; }
}
<div>
hello
</div>

It's important to note that your code will render in red on non-Chromium browsers due to lack of support for CSS nesting. In such cases, these browsers consider the @media rule invalid and focus on parsing the div rule instead.
To ensure compatibility across all browsers, you'll need to manually unwrap these rules:

@media (min-width: 0px) {
  div { color: blue; }
}
div {
  color: red;
}
<div>
hello<!-- will be styled in red universally -->
</div>

Answer №2

To further elaborate on your issue, let me provide another example:

div {
  & {
    color: blue;
  }
  color: red;
}
<div>
  hello
</div>

The concept of "nested rules" and "declarations" can sometimes be confusing, but according to the Specification, the browser will interpret them by placing the "nested rules" at the end.

Therefore, your original code will be reordered like this:

div {
  color: red;
  & {
    color: blue;
  }
}
<div>
  hello
</div>

Eventually, it will be structured as follows:

div {
  color: red;
}

div {
  color: blue;
}
<div>
  hello
</div>

Remember, always organize your code with "declarations" first before adding any "nested rules."

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 steps can I take to unite these two elements?

I'm having trouble adjusting the spacing between the #bigimage and #textarea elements while keeping them centered as a col-12 on small screens. Do you think using a media query would solve this issue? I attempted to place them in a separate container ...

Toggle menu using jQuery to show and hide options

I'm currently working on a menu that should open when the button is clicked once and close when clicked again. I had done this before but I seem to have forgotten how to achieve it. Here is the code snippet that I tried to use: var main = function() ...

Instructions for incorporating a glyphicon glyphicon-calendar into a bootstrap dropdown using pug

I am a beginner in the world of pug and I'm trying to include the glyphicon glyphicon-calendar in a dropdown menu labeled "All months". .pull-right select.form-control.btn-primary#selectMonth(style="margin-top: -15px;") option(selected="selecte ...

The CSS background-image property is not displaying the desired image

Hello there! I'm a beginner in web development and currently working on a small website using HTML, Bootstrap, and CSS. However, I'm facing an issue with the background-image property in my CSS file. I've double-checked the path and the file ...

Navigational dropdown menu item vanishing upon hover

Utilizing bootstrap for my website, the main navigation employs dropdowns for secondary choices. I am encountering an issue in IE10 only (works fine everywhere else) where the dropdown menu is inconsistently accessible. Additionally, if you manage to acce ...

Concealed div obstructing access to dropdown menu

I'm having some trouble creating a dropdown menu. The submenu I've created is appearing behind my wrapper, page, and content. I've attempted to adjust the z-index of various elements and have even tried setting the z-index of my menu and sub ...

What are some ways I can make my content come alive on my website using the Tympanus examples

After spending hours searching for a way to add animation to my content, I finally found a technique that seemed promising. Despite following the same steps as outlined in the tutorial I found, I was disappointed to discover that there was no animation o ...

Difficulty altering link hover background color

I'm having trouble changing the hover effect background-color on the tweets of this page: Despite my efforts, all the links except for the latest tweets are working perfectly. What am I missing? Here's what I've been trying... <script& ...

Browsing through Chrome and Firefox using HTML interface

Hey everyone, I'm facing a few issues with displaying HTML and could use some help: Currently, I have a background image set for the <body></body> element of my HTML page using the following CSS: body { background: url('XYZ.j ...

Style sheets for two dynamically-sized boxes side by side

There are two boxes or columns positioned on the same line. Both have varying widths that need to remain on the same row. To clarify: .----------container 570px-----------. |[box1] [box2]| Ideal scenario | ...

Tips for utilizing the not CSS selector in your stylesheet without the asterisk

My challenge lies here: I am facing an issue with my External Style Sheet where the "*" selector is defined as follows: * { margin: 0em 4.2em 0em 0em; padding: 0em; } The problem arises when I have a tree view control in my aspx page. The above selector ...

Is it possible to eliminate the input border within React-Bootstrap?

Struggling to remove the input borders of the Form.Control component in React-Bootstrap. Despite searching for answers, nothing has been able to solve this issue. I've attempted redefining the .css classes "input" and "form-control", trying to set th ...

Keep some table columns locked in place on your webpage while others are located off-screen, requiring a scroll to access

I have a question regarding an HTML table. There is a windows application that features a vertical scrollable table where some columns are fixed on the page while others remain outside the page. Here is an example: The black border represents the responsi ...

Incorporating Local Storage into a To-Do List Application

I followed a tutorial from w3schools to create a custom task list, tweaking the code to fit my requirements. My goal is to ensure that when I click the save button in the toolbar at the top and then refresh the page, the added tasks are preserved. I&apos ...

Tips for eliminating white frames or borders on the Mapbox canvas map

In my current project using Angular 10, I have integrated Mapbox to display path routes. Following the standard Angular practice of splitting components, I separated the map rendering component and called it into the main map component. However, I encounte ...

I'm seeking a way to access the input element within the InputGroup component of BlueprintJs in my

The BluePrintJS React InputGroup component offers a convenient user interface for modern applications. However, it does not provide direct access to the internal <input> element. There are two primary reasons why I need to access the input element: ...

Achieving Perfect Alignment of Items in a Div With Centering

I've been struggling to center items both vertically and horizontally within a div. Despite searching on various platforms, I haven't been able to find a working solution. My goal is to have each item perfectly centered in its respective div, whe ...

Trouble initializing jSignature on multiple pages with jQuery Mobile

My jquery mobile app is displaying 3 jsignature divs correctly on certain pages, but not on others. The problem arises when the div shows up with a squished height and is unresponsive to touch: Currently, I'm loading these divs using a document ready ...

Zooming on a webpage is causing problems

One issue I'm facing is with the elements on my page acting strange when I zoom in and out. Everything seems to be working fine except for a container div that should overlay a color over the image background. When I zoom in or switch to mobile view, ...

Repairing a CSS file for Internet Explorer versions 7, 8, and 9

Does anyone have experience with troubleshooting HTML5 CSS3 layouts across different browsers? I recently created a website layout from scratch that looks perfect in Firefox 5, Safari 5.1 and Chrome 12 on Mac. However, when using tools like Adobe BrowserL ...