0

I am trying to select only children of a div using CSS.

HTML:

<div class="wrapper">
  <div>Child
    <div>GrandChild</div>
  </div>
  <div>Child</div>
  <div>Child</div>
</div>

CSS:

.wrapper div:first-child {
  display: inline-block;
}

Fiddle: https://jsfiddle.net/781vcf4L/3/

The above CSS applies the CSS property only to a grandchild. I removed the :first-child part and it applies the property to all divs (children and grandchild).

This is what I am trying to achieve:

<div class="wrapper">
  <div style="display: inline-block">Child
    <div>GrandChild</div>
  </div>
  <div style="display: inline-block">Child</div>
  <div style="display: inline-block">Child</div>
</div>

How can I apply the CSS property to children only?

Greg
  • 503
  • 5
  • 30

1 Answers1

4

A space between two selectors is the descendant combinator which, unsurprisingly, selects all descendants including children and grandchildren.

Replace it with the child combinator (>) which selects only children.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • Great! It worked. Thank you for lesson. I will have a read on those :) Thank you once more! – Greg Sep 03 '18 at 15:30