CSS:如何设置第一个列表中第一个 Link 的第一个字母的样式?

CSS: How do I style the first Letter, of the first Link, in the first List?

我对 CSS 不起作用并不感到惊讶,但我希望你能理解。有 2 个列表,我试图在第一个 ul 中定位第一个 a 的第一个字母。在此示例中,它是 Beauty Salons。我可以在不更改 HTML 的情况下使用 CSS 执行此操作吗?

CSS:

.tab-pane .category-headings ul:first-of-type a:first-of-type::first-letter {
    margin-right: 1px;
    padding: 0px 5px;
    background-color: #666;
    color: #fff;
    font-weight: bold;
}

HTML:

<div class="tab-pane" id="b">
    <div class="container-fluid category-headings">
        <div class="row-fluid">
            <div class="span11 offset1">
                <div class="row-fluid">
                    <div class="span4">
                        <ul class="unstyled">
                            <li><a href="./beauty-salons-and-therapy/">Beauty Salons &amp; Therapy</a>
                            </li>
                            <li><a href="./blinds/">Blinds</a>
                            </li>
                        </ul>
                    </div>
                    <div class="span4">
                        <ul class="unstyled">
                            <li><a href="./book-binders/">Book Binders</a>
                            </li>
                            <li><a href="./bookkeeping-services/">Bookkeeping Services</a>
                            </li>
                        </ul>
                    </div>
                    <div class="span4">
                        <ul class="unstyled">
                            <li><a href="./builders/">Builders</a>
                            </li>
                            <li><a href="./building-plans/">Building Plans</a>
                            </li>
                        </ul>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

FIDDLE: http://jsfiddle.net/a4644b8h/2/

如果您将 <a> 标签设置为块显示元素,它会起作用:

.tab-pane .category-headings ul:first-of-type li:first-of-type a:first-of-type::first-letter {
    margin-right: 1px;
    padding: 0px 5px;
    background-color: #666;
    color: #fff;
    font-weight: bold;
}

.tab-pane .category-headings ul:first-of-type li:first-of-type a:first-of-type {
    display: inline-block;
}

这是因为 :first-letter 选择器只适用于块元素,而不适用于内联元素。

Here is an example fiddle.

首先,您需要更改其中的一些 selector。您不是在寻找 ul:first-of-type。这将 select 每个 <div class="span4"> div 中的第一个 ul。相反,你想用 class="span4" 定位第一个 div,像这样:

.span4:first-of-type

接下来,基本相同,您不想定位 a:first-of-type,这将 select 每个 li 元素中的第一个 a 标记.相反,瞄准第一个 li,像这样:

li:first-of-type

然后定位第一个 li

内的 a 标签

因此,将所有这些放在一起:

.tab-pane .category-headings .span4:first-of-type li:first-of-type a::first-letter {

}

此外,正如 Alan 提到的,::first-letter 伪元素的父元素必须是块级元素,因此添加

.span4 a { /* make this selector as specific as you need it */
    display: inline-block;
}

应该就可以了。 JSFiddle here