对第一胎和后代选择器感到困惑

时间:2019-08-28 21:15:52

标签: html css

不想问,但是在这个问题上,长子非常困惑。

    <div class="container">
        <div class="row">
            <div class="col-4">
                <a href="#" class="btn">Primary Button |<span> red text here</span></a>
            </div>
            <div class="col-4">
                <a href="#" class="btn">Secondary button |<span> yellow text here</span></a>
            </div>
            <div class="col-4">
                <a href="#" class="btn">Danger Button |<span> green text here</span></a>
            </div>
        </div>
    </div>

我拥有的CSS是...

 .row span:first-child {
        color: red;
    }
    .row span {
        color: yellow;
    }
    .row span:last-child {
        color: green;
    }
        
        <div class="container">
            <div class="row">
                <div class="col-4">
                    <a href="#" class="btn">Primary Button |<span> red text here</span></a>
                </div>
                <div class="col-4">
                    <a href="#" class="btn">Secondary button |<span> yellow text here</span></a>
                </div>
                <div class="col-4">
                    <a href="#" class="btn">Danger Button |<span> green text here</span></a>
                </div>
            </div>
        </div>

出于某种原因,所有文本颜色都变成“绿色”,因为它应用了所有颜色更改,甚至是红色和黄色,因为它认为它们是该范围的第一个和最后一个孩子。我该怎么做才能使跨度为每个文本设置正确的文本?

2 个答案:

答案 0 :(得分:3)

  

因为它认为它们是跨度的第一个和最后一个孩子。

不正确。

这是因为span是其父元素(即:first-child)的:last-childa


如果要定位span的后代div,它是其父级的:first-child(即.row的后代)…那么您必须编写一个与div相匹配的选择器。

.row div:first-child span {

答案 1 :(得分:1)

您可以通过针对col-4类并使用相同的:first-child /:last-child逻辑来实现所需的效果。这将起作用,因为第一个col-4是.row div的第一个孩子,而最后一个是.row div的最后一个孩子。

然后将内部的跨度作为目标并对其进行适当着色。

.col-4:first-child span {
        color: red;
  }

.col-4 span {
    color: yellow;
}

 .col-4:last-child span {
    color: green;
 }
<div class="container">
            <div class="row">
                <div class="col-4">
                    <a href="#" class="btn">Primary Button |<span> red text here</span></a>
                </div>
                <div class="col-4">
                    <a href="#" class="btn">Secondary button |<span> yellow text here</span></a>
                </div>
                <div class="col-4">
                    <a href="#" class="btn">Danger Button |<span> green text here</span></a>
                </div>
            </div>
        </div>