具有全宽边框的嵌套列表项?

时间:2015-12-03 19:22:50

标签: html css css3

我有一个无序列表,其中有多个嵌套项目,最多可达5级。 要分隔每个列表项,我按如下方式添加border-bottom



    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>
&#13;
&#13;
&#13;

是否有可能让bottom-border不继承list-item的填充并拉伸整个宽度?我认为可以使用background-image完成,但我更愿意找到纯CSS解决方案。

2 个答案:

答案 0 :(得分:5)

您可以使用绝对定位的伪元素:

&#13;
&#13;
#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;
}
&#13;
<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>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

您可以将填充应用于li,并为ul提供负余量。 (它需要每个级别的新规则

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>