问题
I have a collapsible list implemented using HTML and CSS. The list works properly, but I need a little modification.
Whenever I click an item in the list it expands. But as I click on another item in the same list, the previously expanded element gets collapsed while the clicked one gets expanded.
Please help me to apply the behavior that makes it possible to expand multiple list items at the same time.
I want it to be done in HTML and CSS only.
Here is the implementation I currently have. CSS styles:
.row { vertical-align: top; height: auto !important; }
list { display: none; }
.show { display: none; }
.hide:target + .show { display: inline; }
.hide:target { display: none; }
.hide:target ~ .list { display:inline; }
@media print { .hide, .show { display: none; } }
And the HTML markup:
<div class="row">
<a href="#hide1" class="hide" id="hide1">Expand</a>
<a href="#show1" class="show" id="show1">Collapse</a>
<div class="list">
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>
</div>
</div>
回答1:
If you use a modern browser, you can just use HTML5 like this:
<details>
<summary>See More</summary>
This text will be hidden if your browser supports it.
</details>
回答2:
Pure HTML & CSS
A checkbox and it's :checked
state sounds like a perfect match for your case:
[id^="togList"], /* HIDE CHECKBOX */
[id^="togList"] ~ .list, /* HIDE LIST */
[id^="togList"] + label span + span, /* HIDE "Collapse" */
[id^="togList"]:checked + label span{ /* HIDE "Expand" (IF CHECKED) */
display:none;
}
[id^="togList"]:checked + label span + span{
display:inline-block; /* SHOW "Collapse" (IF CHECKED) */
}
[id^="togList"]:checked ~ .list{
display:block; /* SHOW LIST (IF CHECKED) */
}
<div class="row">
<input id="togList1" type="checkbox">
<label for="togList1">
<span>Expand</span>
<span>Collapse</span>
</label>
<div class="list">
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>
</div>
</div>
回答3:
Based on the answers above, just created a single HTML with CSS and JS embedded for this kind of task. GitHub repo, the link will stay valid as I have no plan to remove it.
来源:https://stackoverflow.com/questions/24977965/collapsible-lists-using-html-and-css