Search code examples
htmlcsshtml-listssublistitems

CSS HTML Sub List Items lines connected to parent


I currently have a task list that is generated dynamically. Each task displays as a list item, and is working. I am trying to add sub tasks. I was able to add 2 sub tasks statically, but more cannot be added, as the lines connecting to the parent task are static. Is is possible to dynamically add sub tasks here, and have a line connect to the parent for each added sub item?

ul {
  list-style: none;
}

ul.main::before {
  content: "";
  border: solid 2px black;
  border-width: 0 0 0 2px;
  position: absolute;
  height: 160px;
  margin-left: 10px;
  z-index: -1;
}

.items::before {
  display: inline-block;
  content: "";
  border: solid 2px black;
  width: 25px;
  height: 25px;
  margin-right: 10px;
  background: white;
}

.subitems1,
.subitems2 {
  margin-left: 50px;
  border: solid 2px white;
  text-align: center;
  width: 150px;
}

.subitems1::before {
  position: absolute;
  display: inline-block;
  content: "";
  border: solid 2px black;
  border-width: 0px 0px 2px 2px;
  border-radius: 0 25px;
  width: 54px;
  height: 25px;
  margin-left: -110px;
  margin-top: -10px;
}

.subitems2::before {
  position: absolute;
  display: inline-block;
  content: "";
  border: solid 2px black;
  border-width: 0px 0px 2px 2px;
  border-radius: 0 25px;
  width: 63px;
  height: 50px;
  margin-left: -115px;
  margin-top: -40px;
}
<ul class="main">
  <li class="items">Task 1</li>
  <li class="items">Task 2
    <ul>
      <li class="subitems1">Sub Task 1</li>
      <li class="subitems2">Sub Task 2</li>
    </ul>
  </li>
  <li class="items">Task 3</li>
</ul>


Solution

  • You can use pseudo elements to achieve this structure.

    I have wrapped each child with <span> tag and used ::before element on that.

    ul {
      list-style: none;
    }
    
    ul.sub-menu {
      position: relative;
      padding: 0;
      margin-left: 30px;
      margin-top: 10px;
    }
    
    li.item span {
      position: relative;
    }
    
    
    ul.sub-menu li.item span::before {
      content: '';
      height: 100%;
      width: 10px;
      border-bottom: 1px solid #000;
      border-left: 1px solid #000;
      position: absolute;
      bottom: 10px;
      left: -10px;
      z-index: -1;
    }
    <ul class="main">
      <li class="items">Task 1</li>
      
      <li class="items">Task 2
        <ul class="sub-menu">
          <li class="item"><span>Sub Task 1</span></li>
          
          <li class="item"><span>Sub Task 2</span>
            <ul class="sub-menu">
              <li class="item"><span>Sub Task 1</span></li>
              <li class="item"><span>Sub Task 2</span></li>
            </ul>
          </li>
          
        </ul>
      </li>
      
      <li class="items">Task 3</li>
    </ul>