是否有充分的理由list-style
在<ul>
and<li>
或 just上覆盖 CSS <li>
?
6 回答
Per w3.org you can define list-style-type
on any element with display:list-item
.
As far as I know, in modern browsers you can set any element to display: list-item
so that - if you wanted to - you could correctly use the list-style-type
property on any of them.
Example:
<!DOCTYPE html>
<html lang="en">
<head>
<title>12084892</title>
<meta charset="utf-8">
<style>
div span {
display:list-item;
list-style-type: disc;
list-style-position: inside;
}
</style>
</head>
<body>
<div>
<span>One</span>
<span>Two</span>
</div>
</body>
</html>
Trivia tidbit aside, what behavior are you looking to get? If you want different list items in the same list to have different bullets, then you'll need to define the list-style-type
on the li
s themselves. If you want all the li
s within a given ul
to have the same bullet, it's up to you. I typically define this on the ul
, however. It is more intuitive to do it that way for me, personally.
如果您查看CSS 规范,您会发现该属性旨在设置“带有display: list-item
”的元素的样式。
如果未在元素上显式定义该属性,则该属性将被继承<li>
,因此您应该坚持仅将样式应用于<li>
元素。
即使列表样式是从 UL/OL 继承的,您也应该仅将 css 列表样式定义为 li。您可以在一个列表中创建不同的列表样式。例如:
ul.test li {
list-style:disc;
margin:0 0 0 20px;
}
ul li:first-child {
list-style:circle;
}
如果是同一个,没有。只需在您方便的地方定义它;<li>
s 将继承<ul>
'slist-style
除非显式覆盖。
继承将 ' list-style
' 值从元素传递到ol
元素。ul
li
所以我认为你应该只将样式应用于li
元素。
您通常应该只设置list-style
和元素ul
,ol
因为这样可以避免由级联规则引起的意外和不受欢迎的问题。请参阅CSS 2.1 规范中对 `list-style 的描述。
例如,ol li { list-style: upper-roman; }
可能看起来很安全,但请考虑一下:
<ol>
<li>foo
<ul>
<li>bar
</ul>
</ol>
现在,带有“bar”内容的内部li
元素将应用列表样式,因为它也匹配选择器ol li
。(确实,使用选择器ol > li
可以避免这种情况,但它存在浏览器兼容性问题。)
设置ol { list-style: upper-roman; }
反而避免了这个问题,因为现在内部li
不匹配,并且它继承list-style
自其父级ul
(在浏览器默认样式表中具有合适的设置)。
但是,如果您希望某个特定列表项的样式与同一列表中的其他项不同,则需要list-type
直接设置。li
在这种情况下,您通常会使用 id 选择器或仅匹配该特定元素的其他选择器,而不是任何内部li
元素。