How can I show a rule between elements even when they're hidden?

I would like to display lines between divs. In other words, I would like to draw a line on top of each divs, except the first one.

I wrote the following CSS that works well, except that some divs are hidden. Of course, since some divs are hidden, the selector :not(:first-child) no longer do the expected job. Is there a way to solve this issue in pure CSS?

I can’t use display: none to hide the divs for 2 reasons.

  • the elements are collapsible
  • the elements must remain in the flow for text search purpose
.item {
  height: 50px;
  text-align: center;
  vertical-align: middle;
  line-height: 50px;
}

.item:not(:first-child) {
  border-top: 1px solid red;
}

.item.hide {
  overflow: hidden;
  height: 0;
}
<div class="container">
  <div class="item hide">Item 1</div>
  <div class="item hide">Item 1</div>
  <div class="item ">Item 1</div>
  <div class="item hide">Item 1</div>
  <div class="item hide">Item 1</div>
</div>

>Solution :

Use the next element ~ so that two consecutive item divs must not have the HIDE class to show the border.

.item {
  height: 50px;
  text-align: center;
  vertical-align: middle;
  line-height: 50px;
}

.item:not(.hide) ~ .item:not(.hide) {
  border-top: 1px solid red;
}

.item.hide {
  overflow: hidden;
  height: 0;
}
<div class="container">
  <div class="item hide">Item 1</div>
  <div class="item hide">Item 1</div>
  <div class="item ">Item 1</div>
  <div class="item hide">Item 1</div>
  <div class="item hide">Item 1</div>
</div>

Leave a Reply