0

what is the difference between both of this css selectors as both of them give me same effect then makes different using '>'

  1. .abc > p
  2. .xyz p

.abc > p {
    background-color: yellow;
}

.xyz p {
    background-color: red;
}
<h1>Welcome to My Homepage</h1>

<div class="abc">
    <p>I live in Duckburg.</p>
    <h2>My name is Donald</h2>
    <p>I live in Duckburg.</p>
    <p>I live in Duckburg.</p>
    <p>I live in Duckburg.</p>
</div>

<p>My best friend is Mickey.</p>

<p>I will not be styled.</p>

<div class="xyz">
    <p>I live in Duckburg.</p>
    <h2>My name is Donald</h2>
    <p>I live in Duckburg.</p>
    <p>I live in Duckburg.</p>
    <p>I live in Duckburg.</p>
</div>
Vucko
  • 20,555
  • 10
  • 56
  • 107
  • But basically - `.abc > p` will select only the `p` tags that their direct parent is `.abc` while `xyz p` will select any `p` elements that are inside `.xyz` (http://www.w3schools.com/cssref/css_selectors.asp) – Alon Eitan Apr 28 '16 at 11:38
  • Thanks all for the Help – user3541560 Apr 28 '16 at 11:43

3 Answers3

5

Using .abc > p {} would apply to all p elements who are DIRECT descendants of .abc:

<div class="abc">
    <p>I'm affected</p>
    <div class="test">
        <p>I'm not</p>
    </div>
</div>

Using .xyz p {} applies to ALL p elements within .xyz, whether they're direct descendants, grandchildren, great-great grandchildren, etc:

<div class="xyz">
    <p>I'm affected</p>
    <div class="test">
        <p>I'm affected</p>
        <div class="anothertest">
            <p>I'm also affected</p>
        </div>
    </div>
</div>
David Wilkinson
  • 5,060
  • 1
  • 18
  • 32
4

div p

Selects all <p> elements inside <div> elements  

div > p

Selects all <p> elements where the parent is a <div> 
Jainam
  • 2,590
  • 1
  • 9
  • 18
1

The > symbol targets any direct children of a specific section, in your case .abc. Without it, the style also applies to any sub-children of that class.

CmdrSharp
  • 1,085
  • 13
  • 30