Raj
Raj

Reputation: 1437

Seperate css for 4th sub element in a row

I want to have a separate style for each 4th element in a row.My html structure is like this

<main>
   <div class="a">
     <div class="container"></div>
   </div>
   <div class="a">
     <div class="container"></div>
   </div>
   <div class="a">
     <div class="container"></div>
   </div>
   <div class="a">
     <div class="container"></div>
   </div>
</main>

and css is

 .container:nth-child(4n) {
        left: -2rem !important;
    }

So it doesn't reflect on that 4th element.

Any help is highly appreciated. Thanks in advance.

Upvotes: 1

Views: 58

Answers (3)

Shaggy
Shaggy

Reputation: 6796

Given the markup you provided, your selector will never match any of your elements as there is only one child .container element within each .a parent element. What you want to select is the .container child element of every 4th .a parent element, like so:

.a:nth-child(4n)>.container{
    left:-2rem;
}

Note that the above is identical to:

main>div:nth-child(4n)>.container{
    left:-2rem;
}

If you're asking wht the left property isn't being applied to that element then that's because you also need to give it a position. In this case, relative would probably suit your needs best.

.a:nth-child(4n)>.container{
    left:-2rem;
    position:relative;
}

Alternatively, you could also achieve the above with a single property by using the translatex transform function (although transform does still require some prefixing].

.a:nth-child(4n)>.container{
    transform:translatex(-2em);
}

Upvotes: 3

Hunter Turner
Hunter Turner

Reputation: 6894

Since each .container class is surrounded by <div>'s, you cannot select it directly because there is only one child per <div>. If you want to select every element inside the <main>, you can do something like this:

CSS

main .a:nth-child(4n) {
  color: red;
}
<main>
   <div class="a">
     <div class="container">Hello</div>
   </div>
   <div class="a">
     <div class="container">Hello</div>
   </div>
   <div class="a">
     <div class="container">Hello</div>
   </div>
   <div class="a">
     <div class="container">Hello</div>
   </div>
</main>

JSFiddle

Upvotes: 1

Sumit patel
Sumit patel

Reputation: 3903

Update Css

.a:nth-child(4n) {
    left: -2rem !important;
    color:red;
}

Further Link

Upvotes: 1

Related Questions