Home > Software design >  Trying to target child of a parent with subchildren
Trying to target child of a parent with subchildren

Time:10-20

Background: I have 2 different components constructed in Angular, both video cards. They are both being styled from the same stylesheet using scss. There is a logic as to why there are 2 separate components that perform similar functions, but I haven't explained that as that is not the question

Component One's structure:

<div >
    <h4 >Title</h4>
    <img  src="..."/>   
</div>      

Component Two's structure:

<div >
     <div >
           <h4 >Title</h4>
           <img  src="..."/>
    </div>
</div>

Problem Styles applied to .container>img are showing up on .container>parent>img, and likewise for .container>h4

Objective Style .container>img/h4 and .container>.parent>img/h4 separately such that styles from one do not affect the other

I would not like to use the :has pseudo-class as that is not fully supported. Thank you all for your help

CodePudding user response:

.container>.parent .title {
  color: #ff0000;
}

.container .title {
  color: #00ff00;
}
Component One's structure:

<div >
  <h4 >Title</h4>
  <img  src="https://cdn.pixabay.com/photo/2017/05/09/13/33/laptop-2298286__180.png" />
</div>

Component Two's structure:

<div >
  <div >
    <h4 >Title</h4>
    <img  src="https://cdn.pixabay.com/photo/2018/05/08/08/44/artificial-intelligence-3382507__180.jpg" />
  </div>
</div>

This has to do with (direct) children and (general) descendants.

See this these great answers that explain it really well imho.

Basically we have specified a color for both .title classes but have overridden it by restricting them with the > direct child or direct descendant selector

CodePudding user response:

HTML CODE:

<!-- Component One's structure: -->

<div >
  <h4 >Title</h4>
  <img  src="https://cdn.pixabay.com/photo/2017/05/09/13/33/laptop-2298286__180.png" />
</div>

<!-- Component Two's structure: -->

<div >
  <div >
    <h4 >Title</h4>
    <img  src="https://cdn.pixabay.com/photo/2018/05/08/08/44/artificial-intelligence-3382507__180.jpg" />
  </div>
</div>

Solution CSS CODE :

/* Target subchild of Component One's */
.container .title {
  color: #00ff00;
}

/* Target subchild of Component Two's */
.container>.parent .title {
  color: #ff0000;
}

/* Target both Subchild using class selector*/
.title{
  color:green;
}

/* Target both Subchild using element selector*/
div h4{
  color:gray;
}

/* Target both Subchild using child selector*/
div>h4{
  color:orange;
}

/* Target both Subchild*/
div .title{
  color:blue;
}

I hope it will helpful for you. you can take reference from here: CSS SELECTOR CSS SELECTOR REFRENCE

  • Related