问题
This issue is related to CSS pseudo-class. I refer to :last-child just for example, I suppose it happens to all other pseudo-class too.
- Given I have following simple HTML:
<body>
<p>Paragraph1</p>
<p>Paragraph2</p>
</body>
- I add following CSS:
body:last-child{
color:red;
}
<body>
<p>Paragraph1</p>
<p>Paragraph2</p>
</body>
Without space both paragraphs will be marked as red
- When I will set space between .body and :last-child, only second paragraph will be marked as red - that happens in Google Chrome, I see snippet tool doesn't mark any paragraph with red.
body: last-child{
color:red;
}
<body>
<p>Paragraph1</p>
<p>Paragraph2</p>
</body>
Question: Could anyone help me understand why this happens? Maybe anything to read more on behaviour with space and without space for pseudo-class?
回答1:
It's last paragraph not last body.
So, just do this:
body p:last-child{
color: red;
}
Space separates the next level of elements for css selector to work.
回答2:
pseudo-element should always work without Space in between of element and colon .eg
body p:last-child{ color:red; }
回答3:
1. Without spacing
body:last-child {
color: red;
}
<body>
<p>Paragraph1</p>
<p>Paragraph2</p>
</body>
In the above code, all the p
elements are red because color: red
is applied to the body and is applied to the child elements as well. body:last-child
, here :last-child
is w.r.t to the parent and does not mean last child of body element.
2. With spacing
body: last-child{
color:red;
}
The above is invalid syntax and does not apply styling. You can validate your CSS: W3C CSS Validator
3. Solution:
body p:last-child { /* Select the paragraph which is last inside body */
color: red;
}
Avoid using this in SO snippets as the child selectors will be difficult to style. <link>
and <script>
is added/appended to the markup and disrupts the child selector.
回答4:
With body:last-child
, you target the last body (and there is only one). So everything within the body will be colored red.
The body: last-child
doesn't work, because it is invalid.
What you are looking for is body p:last-child
.
来源:https://stackoverflow.com/questions/32309416/different-behavior-for-pseudo-class-with-space-and-without-space