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>

2
  • 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. Commented Sep 20, 2018 at 3:38
  • stackoverflow.com/questions/9311165/… Commented Sep 20, 2018 at 3:42

4 Answers 4

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

Sign up to request clarification or add additional context in comments.

3 Comments

deleting the margin would change his margin he set for the class though.
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.
Why does he have it there is all I'm saying.
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/

Comments

-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;} 

Comments

-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.

1 Comment

give me reason of down voters it's working for me so i can help to solve problem.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.