Home > Article > Web Front-end > What is the difference between css selectors first-child and first-of-type?
Difference: :first-child matches the first child element in the parent element, which can be said to be the first child element in the structure; while :first-of-type matches the same type of child element under the parent element The first one is no longer limited to the first child element, as long as it is the first element of this type.
【Recommended tutorial: CSS video tutorial】
first- in the css selector The difference between child and first-of-type
: The first-child selector is a selector defined in css2, and it is easy to understand from the literal meaning. , which is the first child element, matching the first child element in its parent element.
For example, there is a piece of code:
p:first-child 匹配到的是p元素,因为p元素是p的第一个子元素; h1:first-child 匹配不到任何元素,因为在这里h1是p的第二个子元素,而不是第一个; span:first-child 匹配不到任何元素,因为在这里两个span元素都不是p的第一个子元素;
: The first-of-type selector is a selector defined in css3, and the parent of the matching element is a specific The first child element of the type.
What is the difference between this and :first-child? Let’s look at that piece of code:
p:first-of-type 匹配到的是p元素,因为p是p的所有类型为p的子元素中的第一个; h1:first-of-type 匹配到的是h1元素,因为h1是p的所有类型为h1的子元素中的第一个; span:first-of-type 匹配到的是第三个子元素span。这里p有两个为span的子元素,匹配到的是它们中的第一个。
So, through the above two examples we can draw the conclusion:
:first-child What is matched is the first child element of a certain parent element, which can be said to be the first child element in the structure.
:first-of-type matches the first child element of the same type under a certain parent element. For example, p:first-of-type means that all types are p. The first of its child elements. There is no longer a limit to the first child element here, as long as it is the first element of this type.
For more programming-related knowledge, please visit: Programming Teaching! !
The above is the detailed content of What is the difference between css selectors first-child and first-of-type?. For more information, please follow other related articles on the PHP Chinese website!