0

HTML

<div class="parent">
            <div class="child-1">Navigation Bar</div>
            <div class="child-2">Background Image</div>
            <div class="child-3">Features</div>
        </div>

CSS

.parent div {
    background: rgb(105, 105, 109);
    color: white;
    padding: 10px;
    border: 5px solid black;
    margin: 10px;
}

.child-1 {
    position: fixed;
    top: 0;
    left:0;
    margin:0;
    width:100%;
    box-sizing: border-box;
}

when I inspect the child element in Chrome I expect the margin:0 to be enabled. However the margin:10px is being applied ? How is this behaviour explained ?

enter image description here

ArunM
  • 2,274
  • 3
  • 25
  • 47

1 Answers1

1

Refer this: https://developer.mozilla.org/en-US/docs/Learn/CSS/Introduction_to_CSS/Cascade_and_inheritance#Specificity

Specificity is basically a measure of how specific a selector is — how many elements it could match. As shown in the example seen above, element selectors have low specificity. Class selectors have a higher specificity, so will win against element selectors. ID selectors have an even higher specificity, so will win against class selectors. The only way to win against an ID selector is to use !important.

The amount of specificity a selector has is measured using four different values (or components), which can be thought of as thousands, hundreds, tens and ones — four single digits in four columns:

  1. Thousands: Score one in this column if the declaration is inside a style attribute (such declarations don't have selectors, so their specificity is always simply 1000.) Otherwise 0.

  2. Hundreds: Score one in this column for each ID selector contained inside the overall selector.

  3. Tens: Score one in this column for each class selector, attribute selector, or pseudo-class contained inside the overall selector.

  4. Ones: Score one in this column for each element selector or pseudo-element contained inside the overall selector.

So, going by the rules the second selector .child-1 has only a classname. Hence the score will be 10

The first selector has a class and an element. So the score will be 11

K K
  • 17,794
  • 4
  • 30
  • 39