skip to Main Content

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>

2

Answers


  1. 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>
    Login or Signup to reply.
  2. We can simply remove the border on the hidden divs if you want to keep them, but this leaves a divider at the last visible element

    .item { 
        height: 50px;
        text-align: center;
        vertical-align: middle;
        line-height: 50px;
    }
    
    .item:not(:first-child) { 
        border-bottom: 1px solid red;
    }
    
    
    .item.hide {
        overflow: hidden;
        height: 0;
      border: none;
    }
    <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 ">Item 1</div>
        <div class="item hide">Item 1</div>
    </div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search