CSS_content用法

content搭配:before:after這兩個偽元素,可以插入指定的內容

為了相容於IE8,要使用單冒號的:before,不能使用雙冒號::before

可插入的 Property Values

normal

預設值。可以將原本有插入的content,還原為normal,也就是預設的“none”(nothing 什麼都沒有)

html:

1
2
<p>My name is Niga Higa</p>
<p id="hometown">I live in Ducksburg</p>

css:

1
2
3
4
5
6
7
p:before{
content: "Read this- ";
}
#hometown:before{
/* 將原本插入的"Read this-"給移除 */
content: normal;
}

results:

none

將原本有插入的內容移除掉

html:

1
2
<p>My name is Niga Higa</p>
<p id="hometown">I live in Ducksburg</p>

css:

1
2
3
4
5
6
7
p:before{
content: "Read this- ";
}
#hometown:before{
/* 將原本插入的"Read this-"給移除 */
content: none;
}

results:

counter

Sets the content as a counter
[作法]

  1. 先建立一個變數(myNumber),讓它隨著p元素每一次出現而遞增

  2. 然後在每個p元素前,插入這個counter

html:

1
2
<p>First make a variable (myNumber) and make it increase every time a p element occurs.</p>
<p>Then insert the counter in front of all p elements</p>

css:

1
2
3
4
5
6
p{
counter-increment: myNumber;
}
p:before{
content: counter(myNumber);
}

results:

attr(attribute)

將「屬性」作為插入的內容

範例一

html:

1
<a href="https://www.airbnb.com.tw">(Airbnb)</a>

css:

1
2
3
4
a:after{
/* content後面不用加"" */
content: attr(href);
}

results:

範例二

html:

1
2
<a href="https://www.tripadvisor.com.tw">TripAdvisor</a>
<br><a href="https://www.w3schools.com/cssref/">CSS Reference</a>

css:

1
2
3
a:after{
content: " ("attr(href)")";
}

results:

文字string

插入指定的文字

html:

1
2
<p>My name is Ryan</p>
<p>I live in Ducksburg</p>

css:

1
2
3
p:before{
content: "Read this- ";
}

results:

前引號open-quote

插入前引號

html:

1
2
<p>My name is Ryan</p>
<p>I live in Ducksburg</p>

css:

1
2
3
p:before{
content: open-quote;
}

results:

後引號close-quote

插入後引號

沒有「前引號」,就不能插入「後引號」

html:

1
2
<p>My name is Ryan</p>
<p>I live in Ducksburg</p>

css:

1
2
3
4
5
6
p:before{
content: open-quote;
}
p:after{
content: close-quote;
}

results:

移除前後引號

將插入的前、後引號移除

html:

1
2
<p>My name is Ryan</p>
<p id="hometown">I live in Ducksburg</p>

css:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
p:before{
content: open-quote;
}
p:after{
content: close-quote;
}

/* 移除前引號 */
#hometown:before{
content: no-open-quote;
}
/* 移除後引號 */
#hometown:after{
content: no-close-quote;
}

results:

url(url)

可以用網址插入多媒體(圖片、聲音檔、影片等)

html:

1
2
<p>My name is Zoe</p>
<p>I live in Ducksburg</p>

css:

1
2
3
p:after{
content: url(https://i.ibb.co/WnVF5Q4/twitter.png);
}

results:

自訂bullets的顏色[額外補充]

先移除ulol預設的bullets後,再自己插入一個看起來像bullets的點點(•),並自訂顏色:

html:

1
2
3
4
5
<ul>
<li>Coffee</li>
<li>Tea</li>
<li>Coca Cola</li>
</ul>

css:

1
2
3
4
5
6
7
8
9
10
11
12
13
/* 先移除預設的bullets */
ul li{
list-style: none;
}

ul li:before{
/* 自己插入點點 */
content: "•";
/* 點點右邊的間距 */
padding-right: 5px;
/* 自訂點點的顏色 */
color: orange;
}

results:


教學網址

https://www.w3schools.com/cssref/pr_gen_content.asp

我的codepen練習

https://codepen.io/saffranwang/pen/PgKpmR