MartinY
MartinY

Reputation: 23

Trying to target child of a parent with subchildren

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 class="container">
    <h4 class="title">Title</h4>
    <img class="image" src="..."/>   
</div>      

Component Two's structure:

<div class="container">
     <div class="parent">
           <h4 class="title">Title</h4>
           <img class="image" 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

Upvotes: 0

Views: 95

Answers (1)

Swapnil Sanghvi
Swapnil Sanghvi

Reputation: 100

HTML CODE:

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

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

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

<div class="container">
  <div class="parent">
    <h4 class="title">Title</h4>
    <img class="image" 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

Upvotes: 1

Related Questions