使嵌套的div看起来像css中的列

时间:2018-01-18 10:17:13

标签: css

我有嵌套代表生命树数据的div,例如

<div>
    Hominidae
    <div>
        Pan
        <div>
            Chimpanzee
        </div>
        <div>
            Bonobo
        </div>
    </div>
    <div>
        Homo
        <div>
            Sapiens
        </div>
    </div>
</div>

我想让它看起来像列中的树,即。

Hominidae    Pan    Chimpanzee
                    Bonobo
             Homo   Sapiens

我设想了几个解决方案,特别是三个真正的列和一个网格,但我感觉只是一点点CSS会使这个解决方案更有效率,只要我在CSS中更有能力。其他解决方案都有添加更多JS逻辑的缺点。

4 个答案:

答案 0 :(得分:1)

div{
  width: 400px;
  background: #bbb;
}
div div{
  width: 60%;
  float: right;
  background: rgba(255, 0, 0, .3);
}
<div>
  Hominidae
  <div>Pan
    <div>Chimpanzee</div>
    <div>Bonobo</div>
  </div>
  <div>Homo
    <div>Sapiens</div>
  </div>
</div>

答案 1 :(得分:1)

您可以将CSS grid用于此

&#13;
&#13;
div {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
}

div>div {
  grid-column: 2;
}
&#13;
<div>
  Hominidae
  <div>
    Pan
    <div>
      Chimpanzee
    </div>
    <div>
      Bonobo
    </div>
  </div>
  <div>
    Homo
    <div>
      Sapiens
    </div>
  </div>
</div>
&#13;
&#13;
&#13;

答案 2 :(得分:1)

.container1 {
  float:right; width: 100%
}
.container2 {
  float:right; width: 60%
}
.container3 {
  float:right; width: 50%
}
<div class ="container1">
Hominidae
  <div class ="container2">
  Pan
    <div class ="container3">
    Chimpanzee
    </div>
    <div class ="container3">
    Bonobo
    </div>
  </div>
  <div class ="container2">
  Homo
    <div class ="container3">
    Sapiens
    </div>
  </div>
</div>

答案 3 :(得分:1)

div {
display:flex;    
    }
    
div div{
width:100px;
display:inline-block;
}
<div>
  <div>Hominidae</div>
  <div>        
    <div>Pan</div>
    <div></div>
    <div>Homo</div>            
  </div>
  <div>        
    <div>Chimpanzee</div>
    <div>Bonobo</div>
    <div>Sapiens</div>
  </div>
</div>