7

Is there a way to select one element, immediately following (or preceding) other by pure CSS?

Foe example, hide one of <br> in a <br><br> pair:

<p>text text <br><br>text text <br>text text <br><br>text text</p>
<p>text text <br>text text <br><br>text text <br><br>text text</p>
<p>text text <br><br>text text <br>text text <br><br>text text</p>

and get it prosessed in the end as:

<p>text text <br>text text <br>text text <br>text text</p>
<p>text text <br>text text <br>text text <br>text text</p>
<p>text text <br>text text <br>text text <br>text text</p>

display: none; appled for br + br or br ~ br don't work as described above.

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356

2 Answers2

8

The problem here is that the only thing separating your br elements is text. Sibling combinators in CSS ignore all non-element nodes between elements including (but not limited to) comments, text and whitespace, so as far as CSS is concerned, all of your paragraphs have exactly five consecutive br children each:

<p>  <br><br>  <br>  <br><br>  </p>
<p>  <br>  <br><br>  <br><br>  </p>
<p>  <br><br>  <br>  <br><br>  </p>

That is, every br after the first in each paragraph is a br + br (and by extension also a br ~ br).

You will need to use JavaScript to iterate the paragraphs, find br element nodes that are immediately followed or preceded by another br element node rather than a text node, and remove said other node.

var p = document.querySelectorAll('p');

for (var i = 0; i < p.length; i++) {
  var node = p[i].firstChild;

  while (node) {
    if (node.nodeName == 'BR' && node.nextSibling.nodeName == 'BR')
      p[i].removeChild(node.nextSibling);

    node = node.nextSibling;
  }
}
<p>text text <br><br>text text <br>text text <br><br>text text</p>
<p>text text <br>text text <br><br>text text <br><br>text text</p>
<p>text text <br><br>text text <br>text text <br><br>text text</p>
Community
  • 1
  • 1
BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
0

This is probably unreliable, but works, at least on Firefox:

br {
  display: block;
}

br {
  display: block;
}
<p>text text <br><br>text text <br>text text <br><br>text text</p>
<p>text text <br>text text <br><br>text text <br><br>text text</p>
<p>text text <br><br>text text <br>text text <br><br>text text</p>
Oriol
  • 274,082
  • 63
  • 437
  • 513
  • Yeah, it depends entirely on how the browser chooses to implement the br element - there is no consensus there. In fact, this works only on Firefox. – BoltClock May 27 '15 at 17:12