使用纯CSS创建分层列表

时间:2016-03-03 22:50:12

标签: html css

我想制作一个如下所示的列表:

enter image description here

我不确定这种类型的设计是否有名称,但“分层列表”已经在谷歌上返回了看起来像我想要的结果,所以我在这里称之为。它基本上与用文件系统浏览器看到的UI模式相同(但这不是我的用例)。

我相信我可以通过SVG实现这一目标,但我想知道纯CSS是否有办法?

我尝试过的一件事是使用带有<ul>伪元素的嵌套before,其中包含一个像这样的unicode框绘制字符。到目前为止我所拥有的是:

ul {
  position: relative;
}

li {
  list-style: none;
}

li.child::before {
  content: "┖";
  transform: scale(1, 1.8);
  position: absolute;
  left: 1em;
}
<ul>
  <li>Root</li>
  <ul>
    <li class="child">Child Lv. 1</li>
    <ul>
      <li class="child">Child Lv. 2</li>
    </ul>
    <li class="child">Child Lv. 1</li>
    <ul>
      <li class="child">Child Lv. 2</li>
      <li class="child">Child Lv. 2</li>
    </ul>
  </ul>
</ul>

它看起来很糟糕,我无法想到任何方式实际上有垂直线连接项目,就像我在图像示例中所做的那样。我会很感激任何可以帮助我最接近我的图像示例的技巧。

SVG可能是可以接受的,但我不想为这个UI组件添加任何重量级的库,所以这就是我要求纯CSS的原因。

1 个答案:

答案 0 :(得分:1)

Per @ CBroe关于在伪元素中使用边框的建议这就是我想出的:

$client_id = $this->container->getParameter('acme_social.twitter.client_id');
$client_secret = $this->container->getParameter('acme_social.twitter.client_secret');
li {
  position: relative;
  list-style: none;
}

li.child::before {
  position: absolute;
  left: -1em;
  top: -0.5em;
  border-left-color: black;
  border-left-style: solid;
  border-left-width: 1px;
  border-bottom-color: black;
  border-bottom-style: solid;
  border-bottom-width: 1px;
  content: "";
  width: 1em;
  height: 1.1em;
}

li.child2::before {
  position: absolute;
  left: -1em;
  top: -2em;
  border-left-color: black;
  border-left-style: solid;
  border-left-width: 1px;
  border-bottom-color: black;
  border-bottom-style: solid;
  border-bottom-width: 1px;
  content: "";
  width: 1em;
  height: 2.5em;
}

li.child3::before {
  position: absolute;
  left: -1em;
  top: -3em;
  border-left-color: black;
  border-left-style: solid;
  border-left-width: 1px;
  border-bottom-color: black;
  border-bottom-style: solid;
  border-bottom-width: 1px;
  content: "";
  width: 1em;
  height: 3.5em;
}

body {
  background: white;
}

看起来近乎完美!我们只需要计算当前<ul> <li>Root</li> <ul> <li class="child">Child Lv. 1</li> <ul> <li class="child">Child Lv. 2</li> </ul> <li class="child2">Child Lv. 1</li> <ul> <li class="child">Child Lv. 2</li> <li class="child">Child Lv. 2</li> </ul> <li class="child3">Child Lv. 1</li> </ul> </ul>上方有多少<li>元素不在同一个缩进级别来确定元素的类,这应该很容易用一点javascript。

谢谢@CBroe!

相关问题