skip to Main Content

How to apply CSS margin-bottom: 30px; to first 3 element and not last 3 element below HTML?

<div class="container">
   <div class="card"></div>
   <div class="card"></div>
   <div class="card"></div>
   <div class="card"></div>
   <div class="card"></div>
   <div class="card"></div>
</div>

2

Answers


  1. You can use a pseudo element called nth-child(). This picks particular childs. In this case, you would use

    .card:nth-child(-n+3) {
      margin-bottom: 30px;
    }
    
    .card:nth-child(-n+3) {
      color:red;
    }
    <div class="container">
       <div class="card">7</div>
       <div class="card">6</div>
       <div class="card">5</div>
       <div class="card">4</div>
       <div class="card">3</div>
       <div class="card">2</div>
       <div class="card">1</div>
    </div>

    You use n as a variable. At n = 1, nth-child will be 2, n = 2, nth-child will be 1 and n = 3 nth-child will be 0. It won’t go on to have negative a nth-child.

    Let me know if it works!

    Login or Signup to reply.
  2. .container .card:nth-child(-n+3) {
      margin-bottom: 30px;
    }
    
    .container .card:nth-last-child(-n+3) {
     margin-bottom: 0px;
    }
        <div class="container">
           <div class="card">test</div>
           <div class="card">test</div>
           <div class="card">test</div>
           <div class="card">test</div>
           <div class="card">test</div>
           <div class="card">test</div>
        </div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search