CSS系列之後代選擇器 子選擇器和相鄰兄弟選擇器

2022-07-19 09:30:22 字數 3223 閱讀 7080

css:

h1 em 

html:

<

html

>

<

head

>

<

style

type

="text/css"

>

h1 em

style

>

head

>

<

body

>

<

h1>this is a <

em>important

em> heading

h1>

<

p>this is a <

em>important

em> paragraph.

p>

body

>

html

>

執行結果: 

<

h1>this is a <

span

><

p><

em>important

em>

p>

span

> heading

h1>

執行結果:

下面設定h1的子元素strong標籤的內容為紅色

第二個h1中,因為strong的父元素不是h1,而是em,所以css中的設定不會對它起作用

css:

h1 > strong
html:

doctype html

>

<

html

>

<

head

>

<

style

type

="text/css"

>

h1 > strong

style

>

head

>

<

body

>

<

h1>this is <

strong

>very

strong

>

<

strong

>very

strong

> important.

h1>

<

h1>this is <

em>really <

strong

>very

strong

>

em> important.

h1>

body

>

html

>

執行結果: 

h1和p擁有相同的父元素body,相鄰兄弟選擇器需要緊挨著,只會適用於與h1相鄰的p標籤的內容

css:

h1 + p
html:

doctype html

>

<

html

>

<

head

>

<

style

type

="text/css"

>

h1 + p

style

>

head

>

<

body

>

<

h1>this is a heading.

h1>

<

p>this is paragraph.

p>

<

p>this is paragraph.

p>

<

p>this is paragraph.

p>

<

p>this is paragraph.

p>

<

p>this is paragraph.

p>

body

>

html

>

執行結果:

請記住,用乙個結合符只能選擇兩個相鄰兄弟中的第二個元素

所以h1+p只會對第乙個p作用,再如下面的例子:

只會對兩個列表的第二個及後面的li起作用,對第乙個li不會起作用

css:

li + li
html:

doctype html

>

<

html

>

<

head

>

<

style

type

="text/css"

>

li + li

style

>

head

>

<

body

>

<

div>

<

ul>

<

li>list item 1

li>

<

li>list item 2

li>

<

li>list item 3

li>

ul>

<

ol>

<

li>list item 1

li>

<

li>list item 2

li>

<

li>list item 3

li>

ol>

div>

body

>

html

>

執行結果: 

後代選擇器和子選擇器

後代選擇器 h1 em 選擇器可以解釋為 作為 h1 元素後代的任何 em 元素 有關後代選擇器有乙個易被忽視的方面,即兩個元素之間的層次間隔可以是無限的。例如,如果寫作 ul em,這個語法就會選擇從 ul 元素繼承的所有 em 元素,而不論 em 的巢狀層次多深。div01 ul li div0...

CSS後代選擇器,子選擇器和相鄰兄弟選擇器

平時在 練習中,經常用到後代選擇器,子選擇器也會用到,這裡做個總結 1,後代選擇器和子選擇器區別 寫法不一樣 後代選擇器的標識為 空格 如 ul li ul和li之間用空格隔開 子選擇器的標識為 如 ul li ul和li之間用 隔開 相鄰兄弟選擇器的標識為 如 h1 p h1和p之間用 隔開 功能...

js原生後代選擇器 CSS 後代選擇器

具體應用 後代選擇器的功能極其強大。有了它,可以使 html 中不可能實現的任務成為可能。假設有乙個文件,其中有乙個邊欄,還有乙個主區。邊欄的背景為藍色,主區的背景為白色,這兩個區都包含鏈結列表。不能把所有鏈結都設定為藍色,因為這樣一來邊欄中的藍色鏈結都無法看到。解決方法是使用後代選擇器。在這種情況...