css裡面有名為偽元素的存在,偽元素本身不是一個真正存在的元素,它算是用來選取元素的一個手段,或是用來在物件中插入內容,偽元素透過物件後面加上::來使用
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Incidunt consequatur molestias odit fuga illo adipisci facere esse distinctio neque. Ullam odio asperiores optio praesentium officia totam ipsa labore maiores quo.</p>
p::first-letter{
color: red;
font-size: 30px;
font-weight: bold;
}
::first-letter:選取元素的第一個字
::first-line:選取物件的第一行字,如果有給放大功能,那會一路放大直到,第一行塞不下時
::selection,選取被使用者選取的部分
p::before{
content: "Lorem ipsum dolor sit amet";
color: red;
background-color: darkkhaki;
}
::before,在物件前content的內容,這裡的設定也都是給content的
p:after{
content: "Lorem ipsum dolor sit amet";
color: red;
background-color: darkkhaki;
}
::after,與::before一樣,只是after會插在後面
下面介紹偽類,偽類一樣不是一類別,它更像是指定物件的狀態
:active,當物件遭啟用時的情況
button:active {
background-color: darkkhaki;
}
按下前
按鈕被按下後
H1:first-of-type {
color: lightgreen;
}
<h1>我是第一個H1</h1>
<h1>我是第二個H1</h1>
<h1>我是第三個H1</h1>
H1:first-of-type選擇同層級的第一個H1
<div>
<h1>我是第一個H1</h1>
<h1>我是第二個H1</h1>
</div>
<div>
<h1>我是第一個H1</h1>
<h1>我是第二個H1</h1>
</div>
<div>
<h1>我是第一個H1</h1>
<h1>我是第二個H1</h1>
</div>
<div>
<h1>我是第一個H1</h1>
<h1>我是第二個H1</h1>
</div>
如果有多個被容器包裹的H1,:first-of-type就會多重選擇
:last-of-type:選擇同級中最後一個
:only-of-type:必須是同級中的唯一一個物件才會被選擇
<div>
<h1>我是第一個H1</h1>
</div>
<div>
<h1>我是第一個H1</h1>
<h1>我是第二個H1</h1>
</div>
<div>
<h1>我是第一個H1</h1>
</div>
<div>
<h1>我是第一個H1</h1>
<h1>我是第二個H1</h1>
</div>
H1:nth-child(6){
color: lightgreen;
}
<div>
<h1>我是第一個H1</h1>
<h1>我是第二個H1</h1>
<h1>我是第三個H1</h1>
<h1>我是第四個H1</h1>
<h1>我是第五個H1</h1>
<h1>我是第六個H1</h1>
<h1>我是第七個H1</h1>
<h1>我是第八個H1</h1>
<h1>我是第九個H1</h1>
<h1>我是第十個H1</h1>
</div>
H1:nth-child(數字),nth-child會數到同級中,對應的物件,這裡是對應H1
但是當第n個數不是指定的物件時就不會有效果。
H1:nth-last-child(數字),同上,但是倒過來數
H1:nth-last-child(6){
color: lightgreen;
}
div:nth-of-type(數字),選擇身為子元素中的第幾個物件,像底下指的,是身為子元素的第二個div
div:nth-of-type(2){
color: lightgreen;
}
<div>
<div>我是第一個DIV</div>
<div>我是第二個DIV</div>
<div>我是第三個DIV</div>
<div>我是第四個DIV</div>
<div>我是第五個DIV</div>
</div>
但是將數字改成1時全部都變了
div:nth-of-type(1){
color: lightgreen;
}
這是因為身為父元素的div同時是body的子元素,所以父元素的div被選擇到了,下面將nth-of-type改成選第二個,同時在給body下添加第二個div
div:nth-of-type(2){
color: lightgreen;
}
<div>
<div>我是第一個DIV</div>
<div>我是第二個DIV</div>
<div>我是第三個DIV</div>
<div>我是第四個DIV</div>
<div>我是第五個DIV</div>
</div>
<div>
<div>我是第一個DIV</div>
<div>我是第二個DIV</div>
<div>我是第三個DIV</div>
<div>我是第四個DIV</div>
<div>我是第五個DIV</div>
</div>
可以看到第一個的div成功選到了他的第二個子元素div,但同時第二個div因為是body的第二個子元素所以被選到了
解決辦法,在前面添加條件,下面會變成選擇父容器是div底下的第二個身為子元素的div
div div:nth-of-type(2){
color: lightgreen;
}
)