Reputation: 41
Suppose I have 3 levels of HTML tag elements in a parent child relationship. A is a grandparent. Inside that there is a tag(parent) and inside that tag there is a
tag(child).Now by using CSS I want to change the design of that
(child) tag from the (grandparent) tag using CSS selectors from that (grandparent) id or class name.
Need help on this css trick
<div>
Hi I am grandparent.
<h2>
Hi I am parent.
<p> Hi I am child. </p>
</h2>
<h2>
Hi I am parent.
<p> Hi I am child. </p>
</h2>
<h2>
Hi I am parent.
<p> Hi I am child. </p>
</h2>
<h2>
Hi I am parent.
<p> Hi I am child. </p>
</h2>
<h2>
Hi I am parent.
<p> Hi I am child. </p>
</h2>
</div>
I want the result to be as follows: Make the background color of the
tag to any colour only for the 4th parent. Note that the control should be from the grandparent. This is because I have a *ngfor in the grandparent and I want to write the css for that using nth-child(n) concept.
Upvotes: 3
Views: 2231
Reputation: 346
You can use :nth-child() property of CSS! Try below-given code. I'm also attaching the link for working CodePen. To understand how it works you can play with it!
Visit the pen for more understanding and live demo: https://codepen.io/CUManiar/pen/vqGdze
.grand-parent {
color: blue;
}
.grand-parent h2:nth-child(4) {
color: red;
}
.grand-parent .parent p:nth-child(2) {
color: pink
}
<div class="grand-parent">
Hi I am grandparent.
<h2 class="parent">
Hi I am parent.
<p class="child"> Hi I am grand child. </p>
<p class="child"> Hi I am 2nd grand child. </p>
</h2>
<h2 class="parent">
Hi I am parent.
<p class="child"> Hi I am 2nd child. </p>
</h2>
<h2 class="parent">
Hi I am parent.
<p class="child"> Hi I am 3rd child. </p>
</h2>
<h2 class="parent">
Hi I am parent.
<p class="child"> Hi I am 4th child. </p>
</h2>
<h2 class="parent">
Hi I am parent.
<p class="child"> Hi I am 5th child. </p>
</h2>
</div>
Upvotes: 1
Reputation: 1421
Although your h2
tags shouldn't contain p
tags, this ought to do the trick:
div h2:nth-of-type(4) {
background-color: tomato;
}
div h2:nth-of-type(4) {
background-color: tomato;
}
<div>
Hi I am grandparent.
<h2>
Hi I am parent.
<p> Hi I am child. </p>
</h2>
<h2>
Hi I am parent.
<p> Hi I am child. </p>
</h2>
<h2>
Hi I am parent.
<p> Hi I am child. </p>
</h2>
<h2>
Hi I am parent.
<p> Hi I am child. </p>
</h2>
<h2>
Hi I am parent.
<p> Hi I am child. </p>
</h2>
</div>
Upvotes: 2