CSS选择器后代不起作用

时间:2014-01-29 16:34:52

标签: css css-selectors

我正在使用后代,但 h1 p 不起作用。类型选择器有什么问题

<!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>

2 个答案:

答案 0 :(得分:4)

CSS后代需要子元素(p in 父元素(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 :(得分: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>