Manolo
Manolo

Reputation: 26370

:first-of-type selector doesn't work

I can't explain why it is not working. I have the next HTML:

<div id="show-entrevistas-home">
  <div id="banner-lateral"></div>
  <div id="post-410" class="post-410 type-entrevistas status-publish hentry has-post-thumbnail"></div>
  <div id="post-408" class="post-408 type-entrevistas status-publish hentry has-post-thumbnail"></div>
  <div id="post-406" class="post-406 type-entrevistas status-publish hentry category-destacado has-post-thumbnail"></div>
</div>

and the next CSS:

#show-entrevistas-home div[id*='post-'].type-entrevistas:first-of-type {
   margin-top: 240px !important;    
}

The above CSS works when I remove :first-of-type, but it's not working with it (the first post is not getting the rule) . Any idea of what can be happening here with :first-of-type?

Upvotes: 0

Views: 1476

Answers (2)

Danield
Danield

Reputation: 125473

How about using nth-child:

FIDDLE

#show-entrevistas-home div[id*='post-']:nth-child(2) {
   margin-top: 240px;    
}

Upvotes: 1

Sirko
Sirko

Reputation: 74046

Citing from the MDN docu on :first-of-type:

The :first-of-type CSS pseudo-class represents the first sibling of its type in the list of children of its parent element.

So it specifies type and not class (or even whole selector). In your case the :first-of-type would refer to the <div> with class banner-lateral, whereas all the other selectors refer to the <div>s with the post-x classes.

The intersection of both is empty, hence your style rule never gets applied.


A workaround could be to change the type of the first <div> to something else. It seems that <div> should just hold a banner, so make it an <img> or use a <span> and adjust its behavior accordingly.

<div id="show-entrevistas-home">
  <img id="banner-lateral" />
  <div id="post-410" class="post-410 type-entrevistas status-publish hentry has-post-thumbnail"></div>
  <div id="post-408" class="post-408 type-entrevistas status-publish hentry has-post-thumbnail"></div>
  <div id="post-406" class="post-406 type-entrevistas status-publish hentry category-destacado has-post-thumbnail"></div>
</div>

or

<style>
  #banner-lateral {
    display: block; /* to make it behave like a div */
  }
</style>
<div id="show-entrevistas-home">
  <span id="banner-lateral"></span>
  <div id="post-410" class="post-410 type-entrevistas status-publish hentry has-post-thumbnail"></div>
  <div id="post-408" class="post-408 type-entrevistas status-publish hentry has-post-thumbnail"></div>
  <div id="post-406" class="post-406 type-entrevistas status-publish hentry category-destacado has-post-thumbnail"></div>
</div>

Upvotes: 4

Related Questions