Robin Dijkhof
Robin Dijkhof

Reputation: 19278

Css target element which does not contain the same element

I got the following html on page 1:

//Page 1:
<aside class="sidebar sidebar--medium">
    <junk>Welcome</junk>
</aside>

And the following on page 2:

//Page 2:
<aside class="sidebar sidebar--medium">
    <junk>
        <aside class="sidebar-light sidebar--medium"> //Whatever is in this should not change.
            <morejunk>Hello world!</morejunk>
        </aside>
    </junk>
</aside>

Junk are other div, classes, etc... Important is that all junks are not the same.

I can not change the HTML because I'm writing some CSS for a third-party web app. I can write some custom CSS for the entire application, not just for a single page. Now I want to target (change the color for example) of "Welcome". How can I do this without affecting "Hello world!"

The following CSS changes the color of both string, which I dont wan't. aside{ color: yellow }

Upvotes: 1

Views: 48

Answers (3)

Temani Afif
Temani Afif

Reputation: 272648

You can try using the > selector like this:

aside.sidebar > junk {
  color:red;
}

aside.sidebar > junk *,
aside.sidebar aside {
 color:initial;
}
<aside class="sidebar sidebar--medium">
    <junk>Welcome</junk>
</aside>
<aside class="sidebar sidebar--medium">
    <junk>
        <aside class="sidebar-light sidebar--medium">
            <morejunk>Hello world!</morejunk>
        </aside>
    </junk>
</aside>

Upvotes: 2

Richard Parnaby-King
Richard Parnaby-King

Reputation: 14862

If the number of aside does not change, you can use the pseudo-selector :first-of-type to select only the first aside:

aside:first-of-type>junk {
  color: red;
}
<aside class="sidebar sidebar--medium">
  <junk>Welcome</junk>
</aside>
<aside class="sidebar sidebar--medium">
  <junk>
    <aside class="sidebar-light sidebar--medium">
      <morejunk>Hello world!</morejunk>
    </aside>
  </junk>
</aside>

This way you don't have to worry about resetting the colour of the next aside.

Upvotes: 0

Jithin Raj  P R
Jithin Raj P R

Reputation: 6797

This will work for you:

aside > div{
  color:red;
}
aside > div div{
  color:blue;
}
<aside class="sidebar sidebar--medium">
    <div>Welcome</div>
</aside>
<aside class="sidebar sidebar--medium">
    <div>
        <aside class="sidebar-light sidebar--medium">
            <div>Hello world!</morejunk>
        </aside>
    </div>
</aside>

Hope this was helpful for you.

Upvotes: 0

Related Questions