簡體   English   中英

如何將 css 添加到前 3 個無序列表而不是有序列表?

[英]How to add css to only first 3 unordered list and not to ordered list?

假設有 html 代碼如下

<ul>
   <li>one</li>
   <li>Two</li>
   <li>Three</li>
   <ol>
       <li>3.14</li>
    </ol>
</ul>

我想將前三個無序列表的文本顏色更改為紅色,而不使用 css 對有序列表進行任何更改。

創建 2 個文件

index.html

  <head>
    <link rel="stylesheet" type="text/css" href="style.css">
   <ul class="i">
   <li>one</li>
   <li>Two</li>
   <li>Three</li>
   </ul>

   <ol>
   <li>3.14</li>
</ol>

樣式.css

.i{
    color: red;
}

您可以使用 CSS 子選擇器並將它們與直接后代選擇器組合,這樣它們只適用於直接在ul內的li而不是更往下。

ul > li:nth-child(1), ul > li:nth-child(2), ul > li:nth-child(3) {
... 
}

由於只有 3 個 li 元素,我們可以像這樣應用所有 3 個 li 元素的 css:-

ul>li{
    color:red;
    some more properties;
}

您可以使用子選擇器:

ul>li:first-child {
color:red;
}

ul>li:nth-child(2) {
color:red;
}

ul>li:nth-child(3) {
  color:red;
}

ol li {
  color:blue;
}

如果你有多個 ul 列表,那么你可以添加類,這樣 css 就不會影響其他人。

添加ol li是因為如果ol屬於li ,那么,當您將顏色應用於li時,它也會修改 ol 的顏色。 所以為了防止它,我們必須明確地給ol' li.

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM