2017-05-25 63 views
0

我想选择CSS中特定类型元素的特定匹配样式。CSS:在HTML文档中选择特定类型元素的特定匹配

例如:

<span>Some random stuff</span> 
<p>Occurrence 1 of p</p> 
<ul> 
<li>Random stuff</li> 
<li>More random stuff</li> 
</ul> 
<p>Occourence 2 of p</p> 
<span>Even more random stuff</span> 

我想样式Occourence 1和P 2以不同的方式,在外部CSS。我知道使用内联CSS会更容易,但我需要在外部完成。另外,我知道我可以为p的每个参数使用一个id或class,但是我想看看我能否找到一种方法来做到这一点。

+0

你可以向这些元素添加类吗? – sheriffderek

回答

1

无需添加ID或类,它听起来就像你正在寻找的:nth-of-type CSS伪选择:

p:nth-of-type(2) { 
 
    color: red; 
 
} 
 
li:nth-of-type(1) { 
 
    color: blue; 
 
}
<span>Some random stuff</span> 
 
<p>Occurrence 1 of p</p> 
 
<ul> 
 
    <li>Random stuff</li> 
 
    <li>More random stuff</li> 
 
</ul> 
 
<p>Occourence 2 of p</p> 
 
<span>Even more random stuff</span>

希望这有助于! :)

+0

这太棒了,如果我编辑我的代码,我可以让它工作。然而,是否有一个伪选择器可以找到元素,即使你想选择的元素在另一个元素内?例如,如果第二次出现的p是在一个div中,但第一次不是,并且我仍然可以使用相同的选择器来选择它们。再次,如果没有,那很好,但如果有的话会更容易。 – MTMaster

+1

绝对!伪选择器可以与常规选择器结合使用!只针对** **在'div'内的某些第n个'p'标签,可以使用'div p:n-type-type(x)'。事先陈述'div'意味着它不会将不在'div'父母内部的'p'标签作为目标。你甚至可以使用'div> p:nth-​​of-type(x)'来定位**直接**后代的p标签。 –

1

您可以使用:nth-of-type()选择器来选择您想要不同风格的一个。

p:nth-of-type(1) { 
    /* Code */ 
} 

p:nth-of-type(2) { 
    /* Code */ 
} 

我知道你说你不想添加id,但你可以使用一个class识别元素。

HTML:

<span>Some random stuff</span> 
<p class="first">Occurrence 1 of p</p> 
<ul> 
<li>Random stuff</li> 
<li>More random stuff</li> 
</ul> 
<p class="second">Occourence 2 of p</p> 
<span>Even more random stuff</span> 

CSS:

.first { 
    /* Code */ 
    } 

    .second { 
    /* Code */ 
    } 

如果你只是想拿到第一<p>你可以p:first-of-type如:

p:first-of-type { 
    /* Code */ 
    } 

有许多不同类型的选择你可以选择here

相关问题