Sergino
Sergino

Reputation: 10838

CSS selector for the div insde first of type element

I have HTML like:

<tag1>
 <div class="c"> // need to select that
   <tag1>
    <div class="c"> // do not need that
    </div>
   </tag1>
 </div>
</tag1>

I want to select the div inside the first tag1 to apply CSS rule

I tried tag1:first-of-type c {} but it didn't work.

Upvotes: 1

Views: 77

Answers (4)

Rounin
Rounin

Reputation: 29501

This is fairly straightforward. You just need two rules.

The first rule will select what you need:

aside > .c {
color: rgb(255, 0, 0);
font-weight: bold;
}

The second rule will set the normal styles and simultaneously deselect any element which fits the pattern aside > .c but which is nested any deeper than the first aside:

.c, aside aside > .c {
color: rgb(0, 0, 0);
font-weight: normal;
}

Working Example:

aside {
display: inline-block;
width: 50%;
height: 25%;
padding: 12px;
border: 2px solid rgb(0, 0, 0);
}

aside > .c {
color: rgb(255, 0, 0);
font-weight: bold;
}

.c, aside aside > .c {
color: rgb(0, 0, 0);
font-weight: normal;
}
<aside>
<div class="c"> // need to select this

<aside>
<div class="c"> // do not need that </div>
</aside>

</div>
</aside>

Upvotes: 0

Mario A
Mario A

Reputation: 3363

Your html propably will be surrounded by other tags, for example a body tag. To only target the outer div, simply be more specific.

<body>
<tag1>
 <div class="c"> // need to select that
   <tag1>
    <div class="c"> // do not need that
    </div>
   </tag1>
 </div>
</tag1>
</body>

CSS

body > tag1 > div.c { }

Upvotes: 0

kukkuz
kukkuz

Reputation: 42362

You can't possibly do that in CSS - you will have to hack your way through if you can't change your markup.

  1. Set the style using tag1 .c:first-of-type

  2. Reset the inner tag1 using tag1 tag1 .c:first-of-type selector and <property>: initial.

See demo below:

tag1 .c:first-of-type {
  color: red;
}

tag1 tag1 .c:first-of-type {
  color: initial;
}
<tag1>
 <div class="c">1
   <tag1>
    <div class="c">2
    </div>
   </tag1>
 </div>
</tag1>

Upvotes: 0

Obsidian Age
Obsidian Age

Reputation: 42354

If you want to select both classes inside your tag, you simply need a . in front of the C:

tag1:first-of-type .c {
  color: red;
}
<tag1>
 <div class="c">Outer
   <tag1>
    <div class="c">Inner
    </div>
   </tag1>
 </div>
</tag1>

Of note, it's actually impossible to only style the outer element with your above structure, though you can always get around this by styling the inner element separately with greater specificity:

tag1:first-of-type > .c {
  color: red;
}

tag1:first-of-type tag1 .c {
  color: black;
}
<tag1>
 <div class="c">Outer
   <tag1>
    <div class="c">Inner
    </div>
   </tag1>
 </div>
</tag1>

Hope this helps! :)

Upvotes: 2

Related Questions