user3962113
user3962113

Reputation:

nth-child selecting incorrect element?

I have the following html:

<body>
<div id="left"></div>
<div id="right"></div>
<div id="top"></div>
<div id="bottom"></div>
<h3 id="fancy">
  This is one fancy heading!
</h3>
<p>
  But I am a very plain paragraph
</p>
<p id="fancy"> But I'm fancy too!
</body>

With the following css:

body {
  margin-left: 20px;
}

body :nth-child(7) {
font-family: courier;
}

#fancy {
  font-family: Cursive;
}

I am wondering about the css only changing the paragraph's font to courier when the nth-child is labeled as 7. Every way I count it, I only see it logically being the 6th, 5th (if it is starting at 0) or maybe even 2nd child (if it for some reason is not counting the div's). Can someone explain to me how the "very plain paragraph" is the 7th child of the body?

Upvotes: 0

Views: 181

Answers (3)

anujsoft
anujsoft

Reputation: 81

<div id="left"></div>
<div id="right"></div>
<div id="top"></div>
<div id="bottom"></div>
<h3 class="fancy">This is one fancy heading!</h3>
<p> But I am a very plain paragraph</p>
<p class="fancy"> But I'm fancy too!</p>

/In CSS please make .fancy instead of #fancy/

<style>
body {
  margin-left: 20px;
}

body :nth-child(7) {
font-family: courier;
}

.fancy {
  font-family: Cursive;
}
</style>

Upvotes: 0

mikehobi
mikehobi

Reputation: 116

Like what was mentioned by Paulie_D and Dan, ID's should not be repeated.

If you change the id to a class, you will notice that the 'nth-child' selector has more weight than the class selector. So you will need to either add '!important' like so:

    .fancy {
        font-family: Cursive !important; 
    }

Or include the elements selected:

    p.fancy, h3.fancy {
        font-family: Cursive; 
    }

Upvotes: 0

Dan
Dan

Reputation: 9468

The 7th child is

<p id="fancy"> But I'm fancy too!</p>

(FYI you were missing closing </p> tag)

To make it easier to see, look at this JS Fiddle Demo where I've added color:red; to body :nth-child(7).

To break it down further

body {
  margin-left: 20px; //this is applied to all of your elements
}

body :nth-child(7) {
  font-family: courier; //this is applied to 7th child
}

#fancy {
  font-family: Cursive; 
  //this is applied to all elements with id="fancy" including the 7th child
  //this overwrites font-family: courier;
}

Also as noted by DJ @Paulie_D, don't use an id more than once per page. Instead use class="fancy" and in your CSS .fancy instead of #fancy.

Upvotes: 2

Related Questions