skip to Main Content

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

2

Answers


  1. 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
    
    Login or Signup to reply.
  2. 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>
     
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search