[英]How to get a tree in HTML using pure CSS
這是嘗試僅使用偽元素和邊框:
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;
}
演示 (編輯)
遺憾的是,偽類在即將發布的CSS3規范中定義,目前很少有Web瀏覽器支持它。
它是在教程結束時編寫的。 也許這就是它不起作用的原因。
我相信我已修好它: 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;
}
謝謝大家,有用的答案讓我讀了更多,最后我讀了這篇文章並刪除了對JavaScript的所有依賴,並使用nth-last-of-type
偽選擇器將特殊背景應用於最后的li項目列表(忽略最后一個li之后的ul)。
最終的代碼在這里 。 我會接受我自己的答案,除非有人指出它有些問題。 (在這個階段,我認為與舊瀏覽器的兼容性並不重要。)
感謝@Aram的回答。 @OneTrickPony,你的答案超過了這個菜鳥頭:)我確信它做對了,但對我來說有點太復雜了。
<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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.