stergosz
stergosz

Reputation: 5860

css same class names get same style

HTML:

<div id="wrapper">
  <div class="body">
     text text text
  </div>
  <div class="comment_submit">
       <!-- here goes username text field !-->
       <div class="body">
         <textarea></textarea>
       </div>
       <!-- here goes submit button !-->
    </div>
</div>

CSS:

#wrapper{
  float:left;
  width:100%;
}
#wrapper .body{
  border:1px solid red;
  background:#f5f5f5;
  padding:5px;
}
.comment_submit .body{
  border:2px solid red;
  background:#cccccc;
}

Why does body div which is inside comment_submit div gets the #wrapper .body style and not only the .comment_submit .body style?

i understand that #wrapper .body style includes all .body divs that are inside #wrapper but how i can stop this?

Upvotes: 3

Views: 655

Answers (3)

archil
archil

Reputation: 39501

That is related to Selector Specificity. Simply it means that #id selector (first case) has priority over class selector (second case). You could fix that by

#wrapper .comment_submit .body{
  border:2px solid red;
  background:#cccccc;
}

Upvotes: 0

Derek
Derek

Reputation: 4931

#wrapper .body{} will apply to all .body classes no matter how deep they are, as long as they are still within #wrapper.

I would recommend renaming the .body which is inside the .comment_submit to .comment_submit_body to fix your problem.

Your class names should not be the same for different styles.

Upvotes: 1

Rob W
Rob W

Reputation: 349252

This solves your problem:

#wrapper > .body{
  border:1px solid red;
  background:#f5f5f5;
  padding:5px;
}
  1. #wrapper .body = "Select every .body which is a descendant of #wrapper".
  2. .comment_submit .body = "Select every body class which is a descendant of .comment_submit.

ID selectors have a higher specifity than class selectors, so properties which are defined in the first selector take precedence over the ones from #2.

  • The solution utilises the child selector, >, which says: "Select every .body element which is a direct child of #wrapper.

Upvotes: 3

Related Questions