Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to apply CSS style only to div and not the before pseudo element

Tags:

html

css

I have a html page which has a div looking like this:

<div class="get-this"> blah blah </div>

I have a before pseudoelement on the div and I am trying to apply CSS style only to the div which will not be applicable to the pseudo element.

.get-this:not(::before) {
  padding-top:2px;
}

The style is applied to the entire div. IS it possible to restrict the style only to the div and not the pseudo element?

like image 646
chrisrhyno2003 Avatar asked Oct 20 '25 03:10

chrisrhyno2003


1 Answers

This is a straightforward use of the cascade.

The CSS cascade is intended to enable you to apply general styles to more general selectors and overriding styles to more specific selectors.

Hence:

.get-this {
  padding-top:2px;
}

.get-this::before {
  padding-top:0;
}

Working Example:

.paragraph-one {
color: red;
}

.paragraph-two {
color: blue;
}

.paragraph-one::before {
content: 'Paragraph One: ';
}

.paragraph-two::before {
content: 'Paragraph Two: ';
color: green;
}
<p class="paragraph-one">This is paragraph one. It is red.</p>
<p class="paragraph-two">This is paragraph two. It is blue.</p>
<p>The <code>::before</code> pseudo-element preceding Paragraph Two <em>isn't the same color</em> as the rest of Paragraph Two, because, further down the cascade, an overriding style has been declared for the more specific <code>.paragraph-two::before</code> selector.</p>
like image 192
Rounin - Glory to UKRAINE Avatar answered Oct 21 '25 16:10

Rounin - Glory to UKRAINE