Formatting an indented list in CSS
Let's say I have a list, with an arbitrary number of indentation levels, like so:
Item
Item
Item
Item
Item
Item
Item
Item
Item
Item
Item
If I'm displaying this开发者_开发技巧 list in an HTML document, how can I use CSS to handle the indentation? There might be an arbitrary number of indentation levels (although in practice there isn't going to be more than 5 or so).
I don't want to create an "indent1" class that indents 10 pixels, an "indent2" class that indents 20 pixels, etc - that's clumsy. Is it possible to create a general rule that will indent by a certain distance based on an attribute value, or the position of an element in the hierarchy?
You would do like so:
https://www.w3schools.com/html/tryit.asp?filename=tryhtml_lists_nested2
And style the <li>
elements not to have a bullet if you like.
Just nest your lists, and HTML's default presentation will do this for you, for any number of levels. Your example would be an unordered list <ul> with three list items <li>. The first list item contains the text “Item” and a nested <ul> of one item, which in turn contains a nested list of one item. And so on.
To suppress bullets, include this CSS in your style sheet:
ul { list-style-type: none; }
To suppress indentation of the top-level list, first hide the left margin of all lists, then restore it for nested lists. (Apparently some browsers use padding instead of margin for their default list indentation, so set both to be safe.)
ul { margin-left: 0; padding-left: 0; }
ul ul { margin-left: 1.5em; padding-left: 1.5em; }
HTML should do this for you, so if you leave the margin and padding settings alone for the <li> element and just fiddle with the other settings such as font size, colour etc, everything should work fine.
For example this should make each list item bold and show a circle for the bullet point image and still preserve the indentation:
<style type="text/css">
li
{
font-weight: bold;
list-style-type: circle;
}
</style>
精彩评论