-1

Here I'm using one ID(#mybox) and class(.box) but both are having the same declaration. moreover here working the background color only with ID. apart from the i know only difference between the ID and class but here as comparison with ID and class.it's working with ID what is difference.and in this case what is strongest in both.

<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
<style>
    #mybox{background-color: red;} 
    .box{background-color:yellow;}
</style>
</head>
<body>
    <div id="mybox" class="box">
        boxes block
    </div>
</body>
</html>
Maik Lowrey
  • 15,957
  • 6
  • 40
  • 79
chinni
  • 13
  • 1
  • 6

2 Answers2

1

It's called CSS Specificity.

ID has infinitely more specificity than class.

You can learn more here: https://web.dev/learn/css/specificity/
And a little bit more fun resource https://cssspecificity.com/

owenizedd
  • 1,187
  • 8
  • 17
1

ID wins. Only with !important declaration would the class get the preference.

#mybox{background-color: red;} 
.box{background-color:yellow !important;}
/* yellow */

Note: @owenizedd correctly pointed out !important should be avoided as much as possible.

Maik Lowrey
  • 15,957
  • 6
  • 40
  • 79
  • Important is a bad practice https://developer.mozilla.org/en-US/docs/Web/CSS/Specificity and you should avoid it `!important, however, is bad practice and should be avoided because it makes debugging more difficult by breaking the natural cascading in your stylesheets` – owenizedd Nov 22 '21 at 08:19
  • @owenizedd That is correct. but that was not the point. It was just to show when it is possible to use the class definition over the id definition. – Maik Lowrey Nov 22 '21 at 08:24
  • 1
    Yep, my point also is not for countering your post, more to giving extra note about this would be a great IMO. – owenizedd Nov 22 '21 at 08:27
  • 1
    @owenizedd just a comment: If u would _always_ use important it wouldn´t break the cascading nature xD just kidding – john Smith Nov 22 '21 at 09:03
  • @johnSmith Good to know ;-) – Maik Lowrey Nov 22 '21 at 09:06