skip to Main Content

My HTML is something like this:

<div class="entry">
  <div class="imageContain">
    <img src="photo1">
  </div>
  <div class="title">Blah</div>
  <div class="text">Whatever</div>
</div>
<div class="entry">
  <div class="imageContain">
    <img src="photo2">
  </div>
  <div class="title">Foo</div>
  <div class="text">Some stuff</div>
</div>

I want to style the imageContain in every alternate entry div differently.

In Chrome, this works:

.entry:nth-of-type(odd) {
  .imageContain {
    background-color: red;
  }
}

but Firefox seems to ignore it

Both Chrome and Firefox ignore this:

.entry:nth-of-type(odd).imageContain {
  background-color: red;
}

How can I address the imageContain divs inside alternate entry divs, please?

2

Answers


  1. You are missing a space:

    .entry:nth-of-type(odd) .imageContain

    About you original code:

    .entry:nth-of-type(odd) {
      .imageContain {
        background-color: red;
      }
    }
    

    It is currently not supported for all browsers.
    https://caniuse.com/css-nesting

    Here when was added to Chrome: https://developer.chrome.com/blog/whats-new-css-ui-2023/#nesting

    The space works because it is the "descendant" selector. Here is the list of all selectors
    https://www.w3schools.com/cssref/css_selectors.php

    Update You probably see this type of code structure on systems like:
    CSS Preprocessors – Sass or Less

    Login or Signup to reply.
  2. The reason why the second CSS selector doesn’t work is because it’s trying to select both the .entry:nth-of-type(odd) and .imageContain elements at the same time.

    To get the desired functionality, you can use the following CSS selector:

    .entry:nth-of-type(odd) > .imageContain {
        background-color: red;
    }
    

    This selector will select all .imageContain elements that are children of .entry elements that have an odd nth-of-type value.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search