简体   繁体   English

带li标签的css“第一个孩子”

[英]css “first-child” with li tag

   <ul>
        <li class="bla">aaa</li>
        <li class="my_li">sss</li>
        <li class="my_li">ddd</li>
        <li class="my_li">fff</li>
    </ul>

css: CSS:

    .my_li:first-child{
            color: #090;
    }

this not working, if make for first li tag class not "bla", but "my_li", alreday li element set green color. 这不起作用,如果使第一个li标记类不是“ bla”,而是“ my_li”,那么li元素设置为绿色。 Someone tell please, why this happened. 有人告诉我,为什么会这样。

The first element that is a member of the class "my_li" is the second child of its parent. 属于类“ my_li”的第一个元素是其父级的第二个子级。

:first-child selects elements that are the first child of their parent. :first-child选择作为其父级的第一个孩子的元素。

You should use this selector: 您应该使用此选择器:

.my_li:nth-child(2) { ... }

(if I'm understanding your question currently and you want the 2nd <li> to have this style) (如果我当前正在理解您的问题,并且您希望第二个<li>具有这种样式)

It doesn't work because that selector means you're choosing an element with class my_li which is the first child of its parent, that is not present in your html. 这是行不通的,因为选择器意味着您正在选择类my_li的元素,该元素是其父级的第一个子级,而该元素不在html中。

Try 尝试

<ul>
    <li class="my_li">aaa</li>
    <li class="my_li">sss</li>
    <li class="my_li">ddd</li>
    <li class="my_li">fff</li>
</ul>

Then your rule will apply to aaa. 然后您的规则将适用于aaa。

http://www.w3schools.com/cssref/sel_firstchild.asp http://www.w3schools.com/cssref/sel_firstchild.asp

If you dont want to change the class for the first element, use : 如果您不想更改第一个元素的类,请使用:

ul li:first-child{
            color: #090;
    }

As Quentin said, :first-child referes to the first element of its parent. 正如Quentin所说, :first-child指的是其父元素的第一个元素。

If you want to target the first element of your example list, do this: 如果要定位示例列表的第一个元素,请执行以下操作:

ul li:first-child {
   color: #090;
}

I think the best solution is to add a second class to your li element 我认为最好的解决方案是在li元素中添加第二类

CSS: CSS:

.first_li{ color:#090; }

<ul>
  <li class="bla">aaa</li>
  <li class="my_li first_li">sss</li>
  <li class="my_li">ddd</li>
  <li class="my_li">fff</li>
</ul>

you could solve your problem with the :nth-child(n) selector, but that means you need to know exactly in which order is the li element inside its parent ul (in this case 2nd child) and if you insert more elements this will fail. 您可以使用:nth-child(n)选择器解决您的问题,但这意味着您需要确切地知道li元素在其父ul (在本例中为第二个孩子)中的顺序,如果您插入更多元素,这将失败。

css: .my_li:nth-child(2){ color: #090;}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM