选择<a> in 1st 2nd 3rd...nth <p> in HTML

时间:2016-05-19 21:31:18

标签: css css3 css-selectors

Here is my HTML code for body.

	<body>
		<!--Add your HTML below!-->
		<p><a href="www.google.com">Google</a></p>
		<p><a href="www.myspace.com">MySpace</a></p>
		<p><a href="www.orkut.com">Orkut</a></p>
	</body>

Now in CSS, I want to target links <a> inside of <p>. So what should I use to select <a> only in 1st <p> without ids, classes etc?

I have tried these but don't work.

p:first-of-type{
    color:#CDBE70;
}

body:nth-child(3) a{
    color:#FFC125;
}

What methods are available in CSS to do so?

2 个答案:

答案 0 :(得分:1)

您未定位第一个选择器中的a,而a标记未继承颜色。如果在选择器中指定锚点,它将起作用。

body p:first-of-type a{
    color:#CDBE70;
}
body p:nth-of-type(2) a{
    color:#0DBE70;
}
body p:nth-of-type(3) a{
    color:#CDB070;
}
<body>
		<!--Add your HTML below!-->
		<p><a href="www.google.com">Google</a></p>
		<p><a href="www.myspace.com">MySpace</a></p>
		<p><a href="www.orkut.com">Orkut</a></p>
	</body>

答案 1 :(得分:0)

试试这个:

p a{
    color:#CDBE70;
}