Back to the basics: blocks in html list
Yesterday, someone (actually working in a team) asked me a question about HTML lists, somewhat surprising I should say:
“I have a list that I need to split in two, to hide half of it, but HTML won’t let me do that”
Here’s what he sent me as an example:
Unfortunately, it just reminded me how easy it is to get into development, and while that’s a good aspect, it can backfire (as it did just there).
What does the specification say?
HTML being a markup language, meaning it defines a structure, and just as for XML, it follows a “strict” structure defined by the W3 HTML working group, that can be found in the HTML 5 specification for instance, if only speaking of the latest version.
Let’s dive in the spec and see what the unordered list (<ul>
) is about:
This specification extract highlights the fact that ul
only supports Zero or more li and script-supporting elements.
. It is therefore not possible to include div
elements as proposed above.
Let’s design a solution
The quick and easy solution is therefore to add the class not on the block but on the list items (li
), and then edit the CSS to hide any li
element with the given class. Classes in CSS are indeed designed to make “groups” of elements.
Hiding half of the items is now super easy, it just requires a very small CSS code: ul > li.groupB { display: none; }
.
authors are encouraged to use values that describe the nature of the content, rather than values that describe the desired presentation of the content.
The quote above comes from the specification again but is rather important in our context. While we will use the groups to display or hide, they should reflect the functional aspect of the item rather than their display status.
While this seems like a decent solution, it is only partially valid. I do agree that most web browser will have no problem at all with the above code snippet, it does not make it 100% valid from a semantic standpoint.
Indeed, the decorative empty line (line 5) let the developer imagine that any of the items in the list will always stay in the given order, which is not what ul
provides.
a list of items, where the order of the items is not important — that is, where changing the order would not materially change the meaning of the document
Using the above, the list is designed to be in this specific order, and one will get a different style, and might not be encouraged to do so. Obviously, there is a solution, and as we’re designing style, it will be a css solution.
ol > li { list-style-type: disc; }
ol > li.groupB { display: none; }
If you have made it so far that’s impressive and I hope you learned something from this article: specifications are awesome and we should read them!
For the given example, I would probably still go for an unordered list (li
) from the context I gathered, what about you, what would you do?