首页 > 解决方案 > 对第一个孩子和后代选择器感到困惑

问题描述

不想问,但在这个问题上对第一个孩子感到非常困惑。

    <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>

某些原因所有文本颜色都变成“绿色”,因为它应用了所有颜色变化,甚至是红色和黄色,因为它认为它们是跨度的第一个和最后一个孩子。我将如何做到这一点,以便跨度为每个跨度设置正确的文本?

标签: htmlcss

解决方案


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

不正确。

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


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

.row div:first-child span {

推荐阅读