Nth-child selector cannot select last child

Below is my html code where I have four passes under the paragraph and I want to do different styles for them.

HTML MARKUP:

<div class="logobar">
    <p>
    <span>Heading text </span><span class="glyphicon glyphicon-chevron-right"></span><span>Audit Creation</span>
    <font class="pull-right">matt@heller.com<span class="glyphicon glyphicon-chevron-down"></span></font>
    </p>
</div>

      

So, to apply the css to all children, I am using the nth-child selector. And when I do this, the first 3 ranges get their css, but the fourth one uses the css of the 1st child. I do not know why?

CSS

.logoBar p span:nth-child(1){
    font-family:ubuntuBold;
    font-size:24px; 
}
.logoBar p span:nth-child(2){
    margin: 0 18px; 
}
.logoBar p span:nth-child(3){
    font-family:ubuntuMedium;
    font-size:18px; 
}
.logoBar p span:nth-child(4){
    margin:0 18px;
}

      

My suggestion:

I think this is because I have the last spacing inside the font tags and therefore is not a direct child of the paragraph. And I have to use the following css for this:

.logoBar p font span:nth-child(1){
        margin:0 18px;
 }

      

Please correct me if I am wrong about some of the standard solutions.

+3


source to share


3 answers


Your guess is correct. nth-child

works relative to that parent, and since it is a tag <font>

, it is the first child (as well as the last), but not the fourth.

.logoBar p *:last-child span{
    margin:0 18px;
}

      



To get around the fact that it is also a range that is the first child, change all the others to be such that they are only a direct child of the paragraph tag

.logoBar p>span...

      

+3


source


just what you need to select the last run as shown

.logoBar p font span{
    margin:0 18px;	
}
      

Run codeHide result


and you need to see that you want to apply the style to the span elements that you provided to the last one.



so i tried a simple one as it might help you what to do.

.logoBar p font span{
    margin:0 18px;
	color :red;	
}
      

<div class="logobar">
    <p>
    <span>Heading text </span><span class="glyphicon glyphicon-chevron-right"></span><span>Audit Creation</span>
    <font class="pull-right">matt@heller.com<span class="glyphicon glyphicon-chevron-down">whats aappppp</span></font>
    </p>
</div>
      

Run codeHide result


+1


source


.logoBar p font span:nth-child(1){
  margin:0 18px;
}

      

Yes you are right. It's because of the font. LogoBar cannot find the fourth child due to a font tag that interferes with the hierarchy. So you need to include the font in your class as well as the nth child number. Also, plz chnage is the logobar class name for logoBar in your HTML code.

+1


source







All Articles