Home > Net >  CSS, given the className of parent element and child element, how to select the child?
CSS, given the className of parent element and child element, how to select the child?

Time:12-01

I have a Reactjs project where I have a below components: I want to hide the div that has a className 'tool' when body has className 'hasModal', and show the 'tool' div when I remove the className 'hasModal'. I know how to remove and add className by using document.body.classList.add/remove And I am using display:none to hide the element. But I do not know how to select the 'tool'element.

<body class="hasModal">
 ...
 many levels of div
 ...
  <div class="tool">
  </div>
</div>

My first intent is to use body.hasModal > div.tool{display: none}, but nothing happened, I can still see the div; I try to use .hasModal.tool {display: none} but that does not take effect; I also use .hasModal>.tool{display:none} but this can not work either. Can someone help me with this? Many thanks!

CodePudding user response:

.hasModal > .tool will not work, because tool has to be a direct child of hasModal and you have "many levels of div" between them.

.b {
  background-color: red;
}

.a > .b {
  background-color: teal;
}
<div class="a">
  <div class="b">
    works
  </div>
</div>

<div class="a">
  <div class="whatever">
    <div class="b">
      works not
    </div>
  </div>
</div>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

.hasModal.tool will not work because it selects all elements that have both classes hasModal and tool.

.b {
  background-color: red;
}

.a.b {
  background-color: teal;
}
<div class="a b">
    works
</div>

<div class="a">
  <div class="b">
    works not
  </div>
</div>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

You should use the "Descendant combinator" which is just a space.

.b {
  background-color: red;
}

.a .b {
  background-color: teal;
}
<div class="a">
  <div class="b">
    works
  </div>
</div>

<div class="a">
  <div class="whatever">
    <div class="b">
      works!
    </div>
  </div>
</div>
<iframe name="sif3" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

See https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors for the details of CSS selectors and how their combinators work.

CodePudding user response:

It's fairly simple to do this:

.hasModal .tool {
  display: none;
}

In CSS, to select a descendant of a class you can use a space between the class names as above.

Additionally you should refer to W3 Schools for more information on CSS selectors

CodePudding user response:

you can search here for how to select selectors https://www.w3schools.com/cssref/css_selectors.asp

  • Related