jomskris
jomskris

Reputation: 305

Select specific element with CSS

I'm trying to select title with CSS selector. This is my css

.category-center :nth-last-child(-n+2) {
    color: red;
}
<div class="category-center">
  <div class="cbp-item-wrapper">
    <div class="post-medias">
      <a href="" target="_blank">
        <img src="#" alt="">
      </a>
    </div>
    <div class="post-info">
      <h4 class="post-title">
        <a href="" target="_blank">This is awesome title</a>
      </h4>
    </div>
  </div>
</div>

Can somebody help me with this?

Upvotes: 1

Views: 229

Answers (2)

cmprogram
cmprogram

Reputation: 1884

Just target the class rather than going specific numnber of children in, as this means if you change your page redesign slightly, it will no longer work.

You can either put a class on your a tag, or target any a tag, on your h4 class, as below.

.post-title a {
  color: red;
}
<div class="category-center">
  <div class="cbp-item-wrapper">
    <div class="post-medias">
      <a href="" target="_blank">
        <img src="#" alt="">
      </a>
    </div>
    <div class="post-info">
      <h4 class="post-title"><a href="" target="_blank">This is awesome title</a></h4>
    </div>
  </div>
</div>

Upvotes: 1

Ankit Agarwal
Ankit Agarwal

Reputation: 30739

You can use .category-center .post-title a. It will target the <a> element which is inside the element with class post-title which is inside category-center element.

You could even use .post-title a but it will break the hierarchy of CSS which you already have for elements inside .category-center. Also, it will tightly bound the HTML with CSS so when in future if you place the HTML outside of .category-center then the styles will not apply and you will know that something is going wrong with that action.

.category-center .post-title a {
  color: red;
}
<div class="category-center">
  <div class="cbp-item-wrapper">
    <div class="post-medias">
      <a href="" target="_blank">
        <img src="#" alt="">
      </a>
    </div>
    <div class="post-info">
      <h4 class="post-title"><a href="" target="_blank">This is awesome title</a></h4>
    </div>
  </div>
    <div class="cbp-item-wrapper">
    <div class="post-medias">
      <a href="" target="_blank">
        <img src="#" alt="">
      </a>
    </div>
    <div class="post-info">
      <h4 class="post-title"><a href="" target="_blank">This is awesome title</a></h4>
    </div>
  </div>
    <div class="cbp-item-wrapper">
    <div class="post-medias">
      <a href="" target="_blank">
        <img src="#" alt="">
      </a>
    </div>
    <div class="post-info">
      <h4 class="post-title"><a href="" target="_blank">This is awesome title</a></h4>
    </div>
  </div>
</div>

Upvotes: 4

Related Questions