Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the first child

I have div with two a tags in it I want to write css for the fist a tag.

Here is the HTML:.

<div id="Text">
    <br />                
    <a href="http://farsnews.com/newstext.php?nn=13920430001427#sthash.BOTOvYwM.dpuf">فارس نیوز</a>
    <a href="http://farsnews.com/newstext.php?nn=13920430001427#sthash.BOTOvYwM.dpuf">فارس نیوز</a>
</div>

and here is my css code:

#Text a:last-child{
    text-decoration: none;
    color: red; /*rgb(18, 139, 235)*/
}
like image 820
Morteza Avatar asked Jun 09 '26 13:06

Morteza


2 Answers

Try this

#Text a:first-of-type{
    /* css */
}

This will select the first <a> tag inside of #Text

like image 194
TotalWipeOut Avatar answered Jun 11 '26 12:06

TotalWipeOut


The problem is that the a is not the first-child within its parent that is DIV#text . The CSS first-child pseudo-class operates as follows:

The :first-child CSS pseudo-class represents any element that is the first child element of its parent.

When ready very literally, it will only apply to an element that is the first child within its parent. It does not take into consideration the context you (mentally) create when you add the additional class selectors to it.

When applying the pseudo-class the browser doesn't understand the context created by the selector. Basically, its checking that the element matches the selector #text a, then asking the question, "Is this the first child within the parent?". It asks this question without any consideration of the aforementioned selector. In your case, the answer is no since there is another element before the first a. that is <br/>(Same thing applied for last-child also)

In your example, the element <br/> is actually the first child.

so the conclusion is-

If you want to give style for a:first-child then it must be a first child of its parent i.e DIV#text

right now your first child is BR so please remove it

OR Else assign

#Text a.q {
  ...
}

Or else

#Text a:first-of-type {...}

The :first-of-type selector is supported in all major browsers, except IE8 and earlier.
like image 25
Chandrakant Avatar answered Jun 11 '26 11:06

Chandrakant



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!