如何为 ul 的第一个元素添加样式?

How to add style to first element of ul?

我正在使用 li 在 HTML 中显示的数组顶部附加一个列表。现在我正在尝试将 css 添加到 li 的第一个 child。我尝试了以下代码。

.ts

this.skills.push({title: 'Play button clicked'});

.html

    <div class="column" class="steps">
        <h2>Steps:</h2>
        <ul *ngFor = "let post of skills" >
            <li>{{ post.title}}</li>
        </ul>
    </div>



.css

.steps li:first-child { 
    background-color: yellow;
}
.steps li:not(::first-line) {
}

我的问题是这个 css 被添加到所有添加的 li 中。除了第一个之外,我不想向 li 显示不同的 css。

您当前的选择器 (.steps li:first-child) 完全没问题;问题是您的 <div> 元素 (<div class="column" class="steps">) 上有 两个 class 属性,这是无效的 HTML。将两者合并为一个属性解决了这个问题,如下所示:

.steps li:first-child {
  background-color: yellow;
}
<div class="column steps">
  <h2>Steps:</h2>
  <ul>
    <li>One</li>
    <li>Two</li>
    <li>Three</li>
  </ul>
</div>

如果你想有多个 <ul> 元素,但只希望突出显示第一个 <ul> 元素的第一个子元素,你需要 .steps ul:first-of-type li:first-child:

.steps ul:first-of-type li:first-child {
  background-color: yellow;
}
<div class="column steps">
  <h2>Steps:</h2>
  <ul>
    <li>One</li>
    <li>Two</li>
    <li>Three</li>
  </ul>
  <ul>
    <li>One</li>
    <li>Two</li>
    <li>Three</li>
  </ul>
</div>

纯Angular方式

HTML

<ul>
  <li *ngFor="let item of array(9); let i = index" [class.firstElem]='i==0'></li>
</ul>

TS

  array(n) {
    return Array(n);
  }

CSS

.firstElem {
  color : red;
}

stackblitz.com

中的工作示例