1

When I view it in the browser, I find that the graphics of div1 are obviously larger than div2. If I change the css style of div2, I will find that div:last-child{} has no effect. I don't know what's going on, can someone help me?

* {
  padding: 0;
  margin: 0;
}

div {
  width: 100px;
  height: 100px;
  background-color: pink;
}

div:first-child {
  background-color: red;
  padding: 10px;
}

div:last-child {
  background-color: blue;
  padding: 10px;
}
<div>1</div>
<div>2</div>

This is the screenshot:

Example of different size divs

Huangism
  • 16,278
  • 7
  • 48
  • 74
kittates
  • 21
  • 5
  • 3
    _"If I change the css style of div2, I will find that div:last-child{} has no effect"_ - then it probably isn't actually the last child of its parent. Use your browser dev tools, to inspect what DOM structure you actually have ... Browser extensions for example often insert their own scripts at the end of body. – CBroe Jan 30 '23 at 14:39
  • 2
    https://jsfiddle.net/2gq4wnvr/ shows the same issue - because jsfiddle itself inserts a script element at the end of body. If you wrap them both in a `section` - which jsfiddle will not insert additional elements into - it looks as expected, https://jsfiddle.net/2gq4wnvr/1/ – CBroe Jan 30 '23 at 14:41
  • Yes, div2 is indeed not the last tag, because I use the Live Server extension, the last element is the script tag – kittates Jan 30 '23 at 14:52
  • Need to use last-of-type, see Rounin's answer, `div:last-child` will target the last child element but not necessarily a div – Huangism Jan 30 '23 at 17:04

2 Answers2

0

It isn't uncommon to see unintended / unexpected results with:

  • :first-child
  • :last-child
  • :nth-child()
  • :nth-last-child()

if the pseudo-class selector the CSS architect requires is actually one of:

  • :first-of-type
  • :last-of-type
  • :nth-of-type()
  • :nth-last-of-type()

If you explicitly want to select the last <div> of a parent element, the correct selector is:

div:last-of-type
Rounin
  • 27,134
  • 9
  • 83
  • 108
-1

If you want to use items selectively like last-first:child, you must first set a reference.

    * {
            padding: 0;
            margin: 0;
        }
        .box {
            width: 100px;
            height: 100px;
            background-color: pink;
        }
.container div:first-child {   
            background-color: red;       
            padding: 10px;
        }
 .container  div:last-child {
            background-color: blue;
            padding: 10px;
        }
<div class="container">
    <div class="box">1</div>
    <div class="box">2</div>
</div>
 
Serdar Göleli
  • 324
  • 2
  • 9