Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

first-child of grandparents

Tags:

html

css

I have multiple divs inside a div. I want the first h1 of the parent div to be underlined. The problem with first-child is it looks at the parent div which in my case is the wrong parent. For example:

        <div class="box">
            <div><h1>first h1 needs to be underlined</h1></div>
            <div>bla bla bla</div>
            <div>bla bla bla2</div>
            <div><h1>big bla bla bla but not underlined</h1></div>
        </div>

I want only the first h1 to be underlined but using .box h1:firstchild will result both h1 to be underlined. Help?

like image 270
Moshe Avatar asked Jan 31 '16 11:01

Moshe


2 Answers

.box > div:first-of-type > h1:first-of-type{
    text-decoration: underline;
}

If you have multiple h1 in first div it will underline only first h1. Just an add to Tims answer

UPDATE JQuery Solution to underline h1 in any first div

var h1Found = false;
$( ".box > div " ).each(function( index ) {

   $(this).find("h1").each(function(){
       if(h1Found) return false;
       $(this).css("text-decoration", "underline" );
       h1Found = true;
   })
});
like image 175
pratikpawar Avatar answered Sep 17 '22 21:09

pratikpawar


Use:

.box > div:first-child > h1 {
    text-decoration: underline;
}

Note that the first-child is applied on the div and not the h1 tag.

like image 37
Tim Avatar answered Sep 17 '22 21:09

Tim