Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nested list-items with full width border?

Tags:

html

css

I have an unordered list with multiple nested items up to 5 levels deep. To seperate each list-item, I'm adding a border-bottom as follows:

    li {
      border-bottom: 1px solid red;
    }
    ul {
      list-style: none;
      padding-left: 1em;
    }
<ul>
  <li>0.1 comment</li>
  <li>0.2 comment</li>
  <li>
    <ul>
      <li>1.1 comment (reply on 0.2)</li>
      <li>1.2 comment (reply on 0.2)</li>
      <li>
        <ul>
          <li>2.1 comment (reply on 1.2)</li>
        </ul>
      </li>
      <li>1.2 comment (reply on 0.2)</li>
    </ul>
    <li>0.3 comment</li>
</ul>

Is there a possibility to have a bottom-border that does not inherit the list-item's padding and stretches the full width? I think it could be done using a background-image, but I'd prefer to find a pure CSS solution.

like image 541
idleberg Avatar asked Mar 14 '23 00:03

idleberg


2 Answers

You can use absolutely positioned pseudo-elements:

#root {
  position: relative;
}
li:after {
  content: '\0200B'; /* Zero-width space to place the border below the text */
  position: absolute; /* Absolutely positioned with respect to #root */
  z-index: -1; /* Place it behind the li, e.g. to avoid preventing selection */
  left: 0;
  right: 0;
  border-bottom: 1px solid red;
}
ul {
  list-style: none;
  padding-left: 1em;
}
<ul id="root">
  <li>0.1 comment</li>
  <li>0.2 comment<br />second line<br />third line</li>
  <li>
    <ul>
      <li>1.1 comment (reply on 0.2)</li>
      <li>1.2 comment (reply on 0.2)</li>
      <li>
        <ul>
          <li>2.1 comment (reply on 1.2)</li>
        </ul>
      </li>
      <li>1.2 comment (reply on 0.2)</li>
    </ul>
    <li>0.3 comment</li>
</ul>
like image 178
Oriol Avatar answered May 04 '23 10:05

Oriol


You could apply the padding to the li and give negative margin to the ul. (it requires a new rule for each level)

ul {
    list-style:none;
    padding-left: 0;
}

li {
  border-bottom: 1px solid red;
}  
/*level 2*/
li li{padding-left: 1em;}
li li ul{margin-left: -1em;}
/*level 3*/
li li li{padding-left: 2em;}
li li li ul{margin-left: 2em;}
/*level 4*/
li li li li{padding-left: 3em;}
li li li li ul{margin-left: -3em;}
/*level 5*/
li li li li li{padding-left: 4em;}
li li li li li ul{margin-left: -4em;}

/*remove double borders*/
li li:last-child{border-bottom:0;}
<ul>
    <li>0.1 comment</li>
    <li>0.2 comment</li>
    <li>
        <ul>
            <li>1.1 comment (reply on 0.2)</li>
            <li>1.2 comment (reply on 0.2)</li>
            <li>
                <ul>
                    <li>2.1 comment (reply on 1.2)</li>
                </ul>
            </li>
            <li>1.2 comment (reply on 0.2)</li>
        </ul>
    <li>0.3 comment</li>
</ul>
like image 36
Gabriele Petrioli Avatar answered May 04 '23 10:05

Gabriele Petrioli