2017-09-11 17 views
2

我正在寻找一种方式来创建<body>的后代<h1><div>的后裔<h2>。我试着用:first-child但这似乎是任何的第一个孩子......样式只是文件中的第一个h1

是否有纯CSS的方式来指定“第一<h1><body>”或“在每一个<div>第一<h2>”?

+0

你为什么不给它一个'id'或'class'并且以这种方式解决它? – ifconfig

+1

@ifconfig我把这个放在一起,对于非技术用户来说,他们会创建html文档 – ControlAltDel

+0

不够公平。我只是好奇,为什么。 – ifconfig

回答

8

更多信息你可能想:first-of-type

div > h2:first-of-type { 
    color: red; 
} 

body > h1:first-of-type { 
    color: red; 
} 
+0

第一个选择器应该是'div> h2:第一个类型'。 – freginold

+0

@freginold好眼睛。更新的 – j08691

1

您可能想要使用first-of-type,下面是单个h1的示例。有关这次访问the w3schools page

h1:first-of-type 
{ 
    color: red; 
} 
2

:first-of-type CSS伪class`代表其类型的一组兄弟元素中的第一个元素。

div > h1:first-of-type { 
    color: black; 
} 

body> h1:first-of-type { 
    color: black; 
} 
+0

第一个选择器应该是'div> h2:first-of-type'。 – freginold

相关问题