【问题标题】:How do i add a style to a specific list element, i.e. single <li> inside <nav> in this?如何将样式添加到特定的列表元素,即 <nav> 中的单个 <li> ?
【发布时间】:2013-01-12 22:58:21
【问题描述】:

我对列表的 CSS 样式有疑问。

这里是代码。

CSS

NAV {
width: 940px;
height: 50px;
float: left;
font-family: Geneva,Arial;
border: 1px solid #000000;
background-color: #D0DBF0;}

NAV ul {
    margin: 0px auto;
    padding-top: 15px;
        padding-left: 70px;
    list-style-type: none;
}
NAV li {
    display: inline;

}

NAV li a {
    float: left;
    text-align: center;
    border-right: 2px solid #00DBF0;
    width: 100px;  
    font-size: 14px; 
    padding: 0px 10px;
    color: #0000FF;
    text-decoration: none;
}

HTML

<NAV>
        <UL>
            <LI><a href="#">Home</a></LI>
            <LI><a href="#">About Us</a></LI>
            <LI><a href="#">Contact Us</a></LI>
            <LI><a href="#">Red Widgets</a></LI>
            <LI><a href="#">Blue Widgets</a></LI>
            <LI><a href="#">Green Widgets</a></LI>
        </UL>
    </NAV>

所以我在这里为导航列表设计了所有内容,但对于第一个列表,即主页。

&lt;LI&gt;&lt;a href="#"&gt;Home&lt;/a&gt;&lt;/LI&gt; 我想要右边框。请帮帮我。

【问题讨论】:

  • 您在标签声明中使用大写字母.. doctype 是什么?

标签: css


【解决方案1】:

您可以使用:first-child 伪类来做到这一点:

nav li:first-child

nav li:first-child a

取决于您是要定位列表项 (&lt;li&gt;) 还是锚点 (&lt;a&gt;)。

【讨论】:

  • 不错不错,但如果我需要为列表中的第二项添加它呢?
  • 使用:nth-of-type 选择器,例如:nth-of-type(2)
  • 好吧,我使用了NAV li a:first-child { border-left: 3px solid red;},但边框被应用到了所有&lt;li&gt; :-(
  • 请注意,我已经为 css 中样式 &lt;nav li a&gt; 中的所有 &lt;li&gt; 赋予了右边框。有什么问题吗?
  • 是的!这使得它:) 谢谢@AnthonyGrist。现在是我学习伪类的时候了! :D
【解决方案2】:

您应该添加一个类或 id。

例如(我们也假设稍后您想要一个“当前选定”项目):

CSS:

.first a { /* specific style for first item */ }
.current a { /* specific style for current item */}

HTML:

<NAV>
        <UL>
            <LI class="first"><a href="#">Home</a></LI>
            <LI><a href="#">About Us</a></LI>
            <LI class="current"><a href="#">Contact Us</a></LI>
            ...

            <!-- if the first item happens to be the curent one: -->
            <LI class="first current"><a href="#">Home</a></LI>
        </UL>
</NAV>

JsFiddle here

【讨论】:

  • css 选择器解决方案似乎更优雅。
  • @DanielCheng 对于 OP 提出的简单案例是正确的。然而,类方法有一些优点:它有更好的browser support,这已经不是什么大问题了。如果您想要一个几乎总是想要的“当前”突出显示的元素,我发现它会更好。但我们不要争论。让这两种解决方案都在这里,每个人都选择合适的。
  • @pinouchon - 它不起作用,因为我已经为整个 &lt;nav&gt; 设置了边框。现在我再次需要给&lt;nav&gt;中的第一个元素添加边框@
  • @PavanNadig 你是对的。您必须在 li 内的 a 上指定样式以覆盖之前的规则。我编辑了我的答案并添加了一个 jsFiddle 以使其正常工作。
猜你喜欢
  • 2018-11-23
  • 2015-12-07
  • 1970-01-01
  • 1970-01-01
  • 2021-06-29
  • 1970-01-01
  • 1970-01-01
  • 2019-01-29
  • 2018-10-16
相关资源
最近更新 更多