I came across the following issue.
I have two HTML sections.
Within the first section, I have an <p> element defined.
The said <p> element comes after a <div> with a class called "text-box"
I have selected this <p> element within my stylesheet by calling in following manner.
.text-box p {
margin: 10px 0 40px;
font-size: 14px;
color: #fff;
}
Then there is a second section and in that there is a second <p> element. I have selected this <p> element in the following manner and applied relevant styling within my style sheet.
p {
color: #fff;
font-size: 49px;
font-weight: 300;
line-height: 22px;
padding: 10px;
background: red;
}
My question is, out of all CSS rules I have defined for the second <p> element, the background: red; rule gets applied to the first <p> element as well. I can not understand why it happens as none of the other rules I have applied are affecting the first <p> element but the background property. I am sure this is something very straightforward I am missing here. Can someone help me, please?
For a better understanding, the HTML and the CSS content are in the following codepen.
All of your styles specified for p will be applied to all p elements except where overridden by specifications for .text-box p which is a more specific selector. For .text-box p, you have replaced the font-size specification from p but you do not have a background specified, so it uses the one you've specified for the more general p.
If you do not want a background for .text-box p, you can unset it with background: unset;.
Doing this with p will overlay all tags with p. But, for example, when you do .mydiv p, it will treat the p inside your div and give it a background.
HTML
<div class="mydiv"> <p>Hello</p> </div>
or
<p class="mytitle">Hi</p>
CSS
.mydiv p{
padding: 40px;
background-color: red;
}
or
.mytitle{
padding: 40px;
background-color: red;
}
Update your second section paragraph tag style by selecting the parent class name course to eliminate any another paragraph outside this section from taking its properties as the following
.course p {
color: #fff;
font-size: 49px;
font-weight: 300;
line-height: 22px;
padding: 10px;
background: red;
}