0

I am trying to understand why the following example does not behave as expected. I have a style that selects general siblings, but I also have children which I would not expect to be selected, but occasionally are. Here is a minimal example that illustrates the problem. The first div>div.h is a descendant, and the ~ does NOT match it. The second p>div.h is clearly a descendant, but the ~ selector DOES match it. I tried in Chrome,Safari and Firefox, all behave the same. I must be missing something. Is p "special"?

<html>
  <head>
    <style>
      .anchor ~ .h { color: orange }
      .anchor2 ~ .h { color: blue }
    </style>
  </head>
  <body>
    <div>
      <div class="h">black 1</div>
      <div class="h">black 2</div>
      <p class="anchor">the anchor</p>
      <div class="h">orange 1</div>
      <div>
        <div class="h">should be black</div>
      </div>
      <p>
        <div class="h">why isn't this black</div>
      </p>
      <div class="h">orange 2</div>
      <p class="anchor2">anchor2</p>
      <div class="h">blue 1</div>
      <div class="h">blue 2</div>
    </div>
  </body>
</html>
keithrel
  • 311
  • 2
  • 4

1 Answers1

2

<div> elements are not valid children of <p>.

Your browser corrects your errors (takes your <div> and places it after <p> instead of inside it) and by doing so, makes div.h a sibling of .anchor:

enter image description here


Now, if you use inline elements in your paragraphs, the browser doesn't correct your markup and you get your expected result:

.anchor ~ .h {
    color: orange
}
.anchor2 ~ .h {
    color: blue
}
<div>
    <div class="h">black 1</div>
    <div class="h">black 2</div>
    <p class="anchor">the anchor</p>
    <div class="h">orange 1</div>
    <div>
        <span class="h">should be black</span>
    </div>
    <p>
        <span class="h">why isn't this black</span>
    </p>
    <div class="h">orange 2</div>
    <p class="anchor2">anchor2</p>
    <div class="h">blue 1</div>
    <div class="h">blue 2</div>
</div>
Community
  • 1
  • 1
George
  • 36,413
  • 9
  • 66
  • 103
  • Ok I understand, the div wasn't actually a child of the p. I found the following official description as well [link](http://www.w3.org/TR/html5/grouping-content.html#the-p-element). The `span` is a nice solution. – keithrel Nov 20 '14 at 21:04