Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I hide only the first element of a type?

I have the following markup:

<div class="ctr-1">
    <h3>Title</h3>
    <div class="ctr-2">
        <h3>Title</h3>
    </div>
</div>

And the following CSS

.ctr-1 h3:first-child{ display:none; }

Both <h3> tags are hidden, I only want the first one hidden. How?

like image 335
Bradley Avatar asked Sep 12 '13 19:09

Bradley


4 Answers

You have wrong, ctr doesn't exist, and you need to tell with > to select the first element level in your page selector try this:

.ctr-1 > h3:first-child{ display:none; }
like image 70
Alessandro Minoccheri Avatar answered Oct 24 '22 04:10

Alessandro Minoccheri


This is what the first-of-type and nth-of-type selectors are for.

For example:

.ctr-1 h3:first-of-type { display:none; }
/* - Or - */
.ctr-1 h3:nth-of-type(0) { display:none; }

This would hide the first h3 descendant of .ctr-1, regardless of its location inside the parent element.

Granted, in your specific example, the h3 is indeed also the immediate (>) and first (:first-child) descendant of .ctr-1 . But if this is a coincidence, you might not be able rely on it. In that case, nth-of-type is the way to go.

like image 31
Boaz Avatar answered Oct 24 '22 06:10

Boaz


You have a few different options:

  1. Use the :first-of-type pseudo class to select the first element of type:

    .ctr-1 > h3:first-of-type {
      display: none; 
    }
    
  2. Or use the :nth-of-type(n) pseudo class and specify the index of the first element:

    .ctr-1 > h3:nth-of-type(0) {
      display: none; 
    }
    
  3. If type doesn't matter, and you always want to select the first child, use the :first-child pseudo class:

    .ctr-1 > h3:first-child {
      display: none; 
    }
    
like image 30
Josh Crozier Avatar answered Oct 24 '22 06:10

Josh Crozier


They are both technically the first-child.

In your example, you could do:

.ctr-1 > h3:first-child { display:none; }
like image 20
crush Avatar answered Oct 24 '22 06:10

crush