Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The specificity of first-line and first-child in CSS?

Tags:

html

css

I have the following html code:

<!DOCTYPE html>
<html>
<head>
<style>
:first-line {
    color: red;
}
:first-child {
    color: blue;
}
</style>
</head>
<body>
<p>asdasdasdsad<br>sdfsdfs</p>
</body>
</html>

The output is:

asdasdasdasd <- red

sdfsdfs <- blue.

However, what I am thinking is that the p tag is the first child of body. first-child is a pseudo-class, which has a specificity of 10 and first-line is a pseudo-element, which has a specificity of 1. Therefore, both lines should be displayed as blue text, but I am apparently wrong.

Please point out my mistake. Thank you very much.

like image 995
Zesen Huang Avatar asked Oct 02 '22 04:10

Zesen Huang


1 Answers

The :first-line selector applies directly to the first line, while the :first-child selector is inherited from the element that it applies to.

A style that applies directly to the item takes precedence over inherited styles.

You can make the selector for the element more specific, by for example adding elements, id and class selectors, but it still can't take precedence over the style applied to the first line. Demo: http://jsfiddle.net/Guffa/3H4Ab/

like image 164
Guffa Avatar answered Oct 12 '22 23:10

Guffa