2014-01-29 87 views
0

我正在使用decendant,但h1 p不起作用。什麼錯類型選擇CSS選擇符不工作

<!doctype html> 
<html> 
    <head> 
      <style> 
     h1 p{ 
       color:blue; 
      } 


      </style> 
    </head> 
    <body> <h1>My first html5 & CSS3 page</h1> 

    <p>The versions of SID and CRUD distributed with SQL Essential Training do not work with PHP warnings enabled. This was fixed before MySQL Essential Training was recorded. The 1.3 version here is the fixed version. (If you have the files from MySQL Essential Training,you already have this.) </p> 

回答

4

CSS後代需要的子元素(p)是的父元素(h1)。

像:

<h1> <p>I'm inside h1</p> </h1> 

那是不是這裏的情況,所以這是不行的。您需要的是下一個兄弟選擇器+~,它們選擇單個以下標記或所有以下標記。

因此,舉例來說:

h1 + p {color:blue;} 

將執行以下操作:

<h1>Example header</h1> 
<p>This paragraph is blue.</p> 
<p>This paragraph is the default color</p> 

和:

h1 ~ p {color:blue;} 

會做什麼:

<h1>Example header</h1> 
<p>This paragraph is blue.</p> 
<p>This paragraph is also blue.</p> 

如果你的標題後有多個段落,我建議使用後者。

如果你想在<h1>後唯一的色彩的段落,但以下<h2>後,你可以這樣做:

h1 ~ p {color:blue;} 
h1 ~ h2 ~ p {color:inherit;} 

這將導致以下:

<h1>Example level 1 header</h1> 
<p>This paragraph is blue.</p> 
<p>This paragraph is also blue.</p> 
<h2>Example level 2 header</h2> 
<p>This paragraph is placed after the level 2 header, so it's not blue anymore.</p> 

inherit值將使段落採用在父元素上定義的顏色(因此爲默認值),這會覆蓋藍色。

Here's a demo。如果您不想阻止級別2標題後面的段落變爲藍色,則可以刪除第二行CSS。

1

這不是一個子元素。您可以使用General Sibling Selector這種情況:

CSS

h1 ~ p{ 
    color:blue; 
} 

HTML

<h1>My first html5 & CSS3 page</h1> 
<p>The versions of SID and CRUD ...</p> 

或者使用一個真正的父元素,例如:

CSS

.parent p{ 
    color:blue; 
} 

HTML

<h1>My first html5 & CSS3 page</h1> 
<div class="parent"> 
    <p>The versions of SID and CRUD ...</p> 
</div> 
+0

嗨,是的請編輯它,所以我知道我通常應該做什麼:)謝謝! – Ezequiel

+0

只需保留必要的部件。 +1保持答案 – DaniP