相邻兄弟和普通兄弟选择器选择不正确

时间:2019-12-21 06:43:41

标签: html css

我尝试使用“相邻同级选择器”和“通用同级选择器”为定位标记后面的段落上色。使用选择器时,第一个元素(故事)未设置样式。前面所有元素的样式都正确。我想知道为什么会这样吗?

html代码如下:

<a class="mylink" href="stories.html" target="_blank" style="color: blue"><img src="abc.png" alt="Image Not Available" height="80" /></a>
<p>Stories</p>

<a class="mylink" href="movies.html" target="_blank" style="color : blue"><img src="abc.png" alt="Image Not Available" height="80" /></a>
<p>Movies</p>

<a class="mylink" href="tables.html" target="_blank" style="color: blue"><img src="abc.png" alt="Image Not Available" height="80" /></a>
<p>Tables</p>

<a class="mylink" href="login.html" target="_blank" style="color: blue"><img src="abc.png" alt="Image Not Available" height="80" /></a>
<p>Login Page</p>

相邻的同级选择器:

a + p {
  color: green;
}

常规兄弟选择器:

a ~ p {
  color: green;
}

1 个答案:

答案 0 :(得分:-2)

这可能是一个特异性问题。选择器正在工作,请参见下面的代码段。您定义的另一种样式可能会覆盖您的样式。在浏览器检查器上,检查<p>元素,如果看到color: green;带有删除线,则表示它已被覆盖。一些浏览器检查器甚至会告诉您哪个其他规则将其覆盖。无论如何,如果您确实找不到特异性问题,请尝试添加!important

a + p {
    color: green;
}
<a class="mylink" href="stories.html" target="_blank" style="color: blue"><img src="abc.png" alt="Image Not Available" height="80"/></a><p>Stories</p>

<a class="mylink" href="movies.html" target="_blank" style="color : blue" ><img src="abc.png" alt="Image Not Available" height="80" /></a><p>Movies</p>

<a class="mylink" href="tables.html" target="_blank" style="color: blue"><img src="abc.png" alt="Image Not Available" height="80"/></a><p>Tables</p>

<a class="mylink" href="login.html" target="_blank" style="color: blue"><img src="abc.png" alt="Image Not Available" height="80"/></a> <p>Login Page</p>

相关问题