0

I thought parent > child would only target children and not grand children elements.

body {
  font-size: 16px;
}
.child {
  border-color: green;
}
.grandchild {
  border-color: blue;
}
.great-grandchild {
  border-color: purple;
}
/* SHOULDN'T THIS TARGET ONLY THE IMMEDIATE CHILDREN ? */
.parent > div {
  font-size: 32px;
  background: #DDD;
}

div {
  padding: 10px;
  border: 1px solid black;
  margin: 5px;
}
    <div class="parent">
      PARENT Font size = 16px as defined by body{}
      <div class="child">
        CHILD: Font size: 32px (as expected)
        <div class="grandchild">
          GRANDHCHILD:<br> Shouldn't font-size = 16px?
        </div>
        <div class="grandchild">
          GRANDHCHILD:<br> Shouldn't font-size = 16px?
        </div>
        <div class="grandchild">
          GRANDHCHILD:<br> Shouldn't font-size = 16px?
          <div class="great-grandchild">
            great grand child<br> Shouldn't font-size = 16px?
          </div>
        </div>
      </div>
    </div>
Johannes
  • 64,305
  • 18
  • 73
  • 130
Kirk Ross
  • 6,413
  • 13
  • 61
  • 104
  • 1
    Your assumption is correct, `.a > *` targets only direct children. `font-size` is an *inherited* property. https://developer.mozilla.org/en-US/docs/Web/CSS/inheritance#Inherited_properties – connexo Dec 08 '18 at 01:10
  • So I need to explicitly set the font size for children of children, and so on, to prevent inheritance? – Kirk Ross Dec 08 '18 at 01:13
  • Exactly. https://stackoverflow.com/questions/5612302/which-css-properties-are-inherited. Each element with no defined `font-size` inherits this from the closest ancestor with a defined `font-size`. – connexo Dec 08 '18 at 01:14
  • You could avoid having to set each and every element by just adding `div:not(.parent) > div { font-size: initial; }` – Tyler Roper Dec 08 '18 at 01:16
  • @TylerRoper That wouldn't do anything in IE 11, though. – connexo Dec 08 '18 at 01:18
  • @connexo OP didn't seem to mention anything about IE11, but in any case you're correct. – Tyler Roper Dec 08 '18 at 01:20
  • If that is a concern, set a font size on `html` rather than `body`, and then you can use `1rem` for a size in the grandchildren: `.parent > div div {font-size:1rem;}` – Mr Lister Dec 08 '18 at 08:37

0 Answers0