Home > Blockchain >  Why does a pseudo-selector style rule on a standard element apply to a related pseudo-element also?
Why does a pseudo-selector style rule on a standard element apply to a related pseudo-element also?

Time:11-18

I am wondering why this code will also change the first letter of h1::before. I search about the CSS specificity--all three of them are same since they all have one element and one pseudo element (if I am wrong, please tell me). Then I think they should follow by order. This is the process in my mind: It will change the first letter of h1, then add a pseudo -element before h1 with content, and then add the pseudo-element after. The first letter won't change. Can anyone help me understand it?

h1::first-letter {
  font-size: 70px;
  font-style: italic;
  color: yellow;
}

h1::before {
  content: "This is";
  color: green;
}

h1::after {
  content: "of Website";
}
<h1>Heading</h1>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

The generated code looks more like this:

<h1>
  ::before
  Heading
  ::after
</h1>

The ::first-letter doesn't "create" a new element, it's different from ::before and ::after.
So as the documentation says:

A combination of the ::before pseudo-element and the content property may inject some text at the beginning of the element. In that case, ::first-letter will match the first letter of this generated content.

And that's why the text inside the ::before gets styled with the ::first-letter properties.

CodePudding user response:

Your misunderstanding may be that CSS is applied in sequential order. This is not the case. CSS is compiled into a structure that applies in its entirety, not as a series of steps or instructions. It's not code.

Any rule that applies to any element in the CSS, and which is not overridden by another later or more specific rule will apply.

  • Related