css child selector expression understanding confuses about the following code walk through

45 views Asked by At

In CSS what does it mean by this? .wb is a class and I also understand that .wb-chIld may be its child classes which inherits properties of that. now what is the > and * ? under which circumstances we write code like this?

.wb, .wb-child > * {
     border-width: 2px;
}
2

There are 2 answers

0
Ruddy On

Lets break it down shall we.

So we have:

.wb, .wb-child > * {
     border-width: 2px;
}

.wb: is a class, anything with this class will have the following defined styles.

.wb, .wb-child > *: Now we have a comma , this allows us to have more then one selector on a style. So in this case there are 2 selectors, both .wb and .wb-child > *.

.wb-child > *: Now lets take a look at what this is selecting. It is pointing at .wb-child and selecting all (* selects all elements) the immediate children of that class.

Lets take a look at this in a demo.

.wb,
.wb-child > * {
  border: 1px solid red;
  margin: 5px;
}
<div class="wb">
  This is some test text.
  <div class="wb-child">
    <span>I am a immediate span child of .wb-child</span>
    <div>I am a immediate div child of .wb-child
      <div>I am a child of this div, not an immediate child of .wb-child</div>
    </div>
  </div>
</div>

In this demo we are giving a border to .wb and all of .wb-child children ( > *). Please note that .wb-child itself does not have a border, only its children do.

Also the div that is inside of .wb-child div is also not affected, this is due to it not being an immediate child of .wb-child.

To learn more about * selector here.

1
Azulite On

EDIT: @misterManSam is right, only the immediate child wb1 will have the border-width: 2px style applied

'.wb-child > *' meant all tags after the 'wb-child' class. Refer to your example with below HTML codes:

<div class="wb-cihld">
  <div class="wb1">
    <div class="wb2">
    </div>
  </div>
</div>

Both 'wb1' and 'wb2' classes will have the 'border-width: 2px;' style applied.