0

div p { margin-bottom: 10px;} is not working. Not sure what is wrong here.

.p1, .p2 {
    margin-bottom: 10px; 
    }

is works fine, but div p {...} is not working.

body {
  position: relative;
  background-color: Royalblue; /*#f0f0f0;*/
  margin: 0px;
}

.div {
    position: relative;
    top: 20px;
    width: 30%;
    margin: 0 auto;
    text-align: center;
    border: 1px solid black;
}

.p1 {
    margin: 0;
}

.p2 {
    margin: 0;
}

div p {
    margin-bottom: 10px;
}
<body>  
        
        <div class="div">
      
            <p class="p1">Welcome to Homepage</p>
            <p class="p2">Lorem Ipsum</p>
            
        </div>
   
</body>
Kiran Shahi
  • 6,458
  • 6
  • 31
  • 60
yalpsid
  • 235
  • 1
  • 9
  • 2
    Because the *class* `.p1` has higher specificity than the combined elements `div p` so that rule takes precedence. The search terms you want are "css specificity"; there are discrete rules which assign "weights" to different selectors to help the browser determine precedence when cascading styles. – Roddy of the Frozen Peas Sep 20 '18 at 03:38
  • https://stackoverflow.com/questions/9311165/how-element-selector-is-more-specific-than-id-selector – Roddy of the Frozen Peas Sep 20 '18 at 03:42

4 Answers4

2

Because of Specificity, the class .p1 rule is overriding the div p rule. If you delete the margin: 0 from the class rule, it should work, as there will be no competition between rules and the 10px can apply.

Some reading: https://developer.mozilla.org/en-US/docs/Web/CSS/Specificity

Ben Steward
  • 1,909
  • 10
  • 19
  • deleting the margin would change his margin he set for the class though. –  Sep 20 '18 at 03:47
  • He never stated that he needed that rule, so I’ll just assume he’s a smart guy and that he will continue reading/learning and figure out a way to make it work if that’s what he actually needs. – Ben Steward Sep 20 '18 at 03:50
  • Why does he have it there is all I'm saying. –  Sep 20 '18 at 03:53
2

Yes it should not work according css selector precedence rules. According css selector precedence rules class selector value is 10 and for tag selector value is 1. So from your code we can calculate easily:

.p1 or .p2 precedence value = 10

div p precedence value is 1 + 1 = 2

That's why it is div p {...} selector not working.

You can learn more from here about CSS precedence rules: https://css-tricks.com/specifics-on-css-specificity/

Hanif
  • 3,469
  • 1
  • 9
  • 15
-1

You have to put either .p1 or .p2. Style the css for each of them separately

.p1 { margin-bottom: 10px;}

.p2 { margin-bottom: 10px;}
Ivana Mica
  • 81
  • 1
  • 1
  • 9
-1

you should try this it help full it's here class inside another class.

Code:

    .div .p1 { margin-bottom: 10px;}

Here (.) is the class identifier.

Pratik Patel
  • 122
  • 9