Как получить дерево в HTML с помощью чистого CSS
Я пытаюсь выполнить этот учебник и здесь мой код пока.
В конце учебника показано, что последние узлы в ветке не будут иметь никаких вертикальных полос после него. Но я не мог заставить его работать так! Любые идеи, если я делаю что-то неправильно, или, возможно, в учебнике отсутствует что-то!
Я попробовал даже псевдо-класс last-child, как показано в учебнике, но получил тот же результат.
![Wrong CSS Tree]()
Ответы
Ответ 1
Здесь попробуйте использовать только псевдоэлементы и границы:
ul, li{
position: relative;
}
/* chop off overflowing lines */
ul{
overflow: hidden;
}
li::before, li::after{
content: '';
position: absolute;
left: 0;
}
/* horizontal line on inner list items */
li::before{
border-top: 1px solid #333;
top: 10px;
width: 10px;
height: 0;
}
/* vertical line on list items */
li::after{
border-left: 1px solid #333;
height: 100%;
width: 0px;
top: -10px;
}
/* lower line on list items from the first level
because they don't have parents */
.tree > li::after{
top: 10px;
}
/* hide line from the last of the first level list items */
.tree > li:last-child::after{
display:none;
}
демо (отредактировано)
Ответ 2
К сожалению, псевдокласс определен в следующей спецификации CSS3, и на данный момент это поддерживает несколько веб-браузеров.
Это написано в конце учебника. Может быть, причина в том, что он не работает.
Ответ 3
Я считаю, что исправил его: https://github.com/gurjeet/CSSTree/pull/1
Я изменил CSS для удаления фона и изменения поля для заполнения.
ul.tree, ul.tree ul {
list-style-type: none;
margin:0;
padding:0;
}
ul.tree ul {
padding-left: 1em;
background: url(vline.png) repeat-y;
}
ul.tree li {
margin:0;
padding: 0 1.2em;
line-height: 20px;
background: url(node.png) no-repeat;
color: #369;
font-weight: bold;
}
/* The #fff color background is to hide the previous background image*/
ul.tree li.last {
background: #fff url(lastnode.png) no-repeat;
}
ul.tree ul:last-child {
background: none;
}
Ответ 4
Спасибо, ребята, полезные ответы, которые заставили меня прочитать еще кое-что, и, наконец, я прочитал эту статью и удалил всю зависимость от JavaScript и использовал псевдо-селектор nth-last-of-type
, чтобы применить специальный фон к последним элементам li в списке (игнорируя ul, который приходит после последнего li).
Последний код здесь. Я собираюсь принять свой собственный ответ, если кто-то не указывает на некоторые проблемы с ним. (Я не думаю, что совместимость со старыми браузерами важна для меня на этом этапе.)
Спасибо @Aram за ответ. @OneTrickPony, ваш ответ прошел через голову этого noob:) Я уверен, что он поступает правильно, но для меня это слишком сложно.
<style type="text/css">
/* ul[class=tree] and every ul under it loses all alignment, and bullet
* style.
*/
ul.tree, ul.tree ul {
list-style-type: none;
margin:0;
padding:0;
}
/* Every ul under ul[class=tree] gets an indent of 1em, and a background
* image (vertical line) applied to all nodes under it (repeat-y)
*/
ul.tree ul {
padding-left: 1em;
background: url(vline.png) repeat-y;
}
/* ... except the last ul child in every ul; so no vertical lines for
* the children of the last ul
*/
ul.tree ul:last-child {
background: none;
}
/* Every li under ul[class=tree]
* - gets styling to make it bold and blue, and indented.
* - gets a background image (tilted T), to denote that its a node
* - sets height to match the height of background image
*/
ul.tree li {
margin:0;
padding: 0 1.2em;
background: url(node.png) no-repeat;
line-height: 20px;
color: #369;
font-weight: bold;
}
/* The last li gets a different background image to denote it as the
* end of branch
*/
ul.tree li:nth-last-of-type(1) {
background: url(lastnode.png) no-repeat;
}