CSS ul 嵌套列表的第一级没有边距?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6568442/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
ul no margin on first level of nested list?
提问by Wesley
I want a styled list that doesn't have a margin-left on the first level.. But does on subsequent, leveled sublists.. Anyone know how to do this?
我想要一个在第一级没有边距的样式列表。
<ul>
<li>no margin</li>
<li>
<ul>
<li>yes margin</li>
</ul>
</li>
</ul>
(without adding css classes to the first level of ul or changing any of the code)
(无需在 ul 的第一级添加 css 类或更改任何代码)
采纳答案by TommyBs
Is the first ul a direct descendant of the body? I know you said not adding css classes to the code but I presume adding stuff to a stylesheet is not out the question? If so you could use a style declaration like:
第一个 ul 是 body 的直系后代吗?我知道你说过不要在代码中添加 css 类,但我认为向样式表添加内容不是问题?如果是这样,您可以使用如下样式声明:
body > ul{
margin-left:0px;
}
or if you know a div it does sit within:
或者,如果您知道一个 div,它确实位于:
#your_id > ul{
margin-left:0px;
}
There may also be default padding you need to consider.
您可能还需要考虑默认填充。
Thanks
谢谢
回答by Paul D. Waite
If you want this to apply to all <ul>
s on every page the stylesheet is applied to, this works:
如果您希望这适用于<ul>
应用样式表的每个页面上的所有s,这有效:
ul {/* Remove margin for all <ul>s (and padding, because different browsers have different default styles) */
margin-left: 0;
padding-left: 0;
}
ul ul {/* Add a margin for any <ul> inside another <ul> */
margin-left: 2em;
}
But if you only want it to apply to certain lists, you need to add something to the HTML to identify those lists (as the other answers have suggested).
但是,如果您只想将其应用于某些列表,则需要在 HTML 中添加一些内容以识别这些列表(如其他答案所建议的那样)。
回答by Jorn
You should probably clear the margin of the main <ul>
, and then set the margin for a <ul>
that's in an <li>
element.
您可能应该清除 main 的边距<ul>
,然后为元素<ul>
中的a 设置边距<li>
。
ul {
margin-left: 0px;
}
li > ul {
margin-left: 10px;
}
回答by paddotk
Indeed, but a small complementation to TommyBs's answer: you need to apply the id you use in the html list item tag, like so:
确实,但对 TommyBs 的回答有一个小小的补充:您需要应用您在 html 列表项标签中使用的 id,如下所示:
<ul>
<li id="your_id">no margin</li>
<li>
<ul>
<li>yes margin</li>
</ul>
</li>
</ul>
And in the css the corresponding line would be
在 css 中,相应的行是
li#your_id {
margin-left:0px;
}
回答by my9006
In my case there was default margins, and I set them 0
-webkit-margin-before: 0;
-webkit-margin-after: 0;
-webkit-padding-start: 0;
就我而言,有默认边距,我将它们设置为 0
-webkit-margin-before: 0;
-webkit-margin-after: 0;
-webkit-padding-start: 0;