2

Suppose I have a CSS class:

.text-red {
  color: red;
}

This class is defined elsewhere, may be supercomplex, and is not editable.

In my DOM I have several paragraphs. I want to apply text-red class to all paragraphs. Of course I may write that directly:

<p class="text-red">XXX</p>
<p class="text-red">YYY</p>
<p class="text-red">ZZZ</p>
<p class="text-red">WWW</p>

but it is so redundant. I'd like to write in my CSS file something like:

p {
  .text-red
}

so that all "p" elements have that class applied. Clearly this is not a CSS valid rule. How may I do?

2
  • You can do this with one line of js or jquery, would you like to see that solution? or are you going for purely css? Commented Feb 2, 2018 at 19:36
  • Yes, purely css Commented Feb 2, 2018 at 19:39

3 Answers 3

0

You can easily do so with SASS pre-processor by using @extend.

https://sass-lang.com/guide

Ohterwise, you could use JavaScript (jQuery) as well:

$('p').addClass('.text-red')

But maybe the easiest would be to copy the properties to the p selector?

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

2 Comments

How would you do in SASS? I tried with: p { @extend .text-red } But I get: The selector ".text-red" was not found. Clearly the class do exists, but it comes from a standard css file, so I guess SASS is not seeing it...
You're on a good way! I would change the original file to '.scss' and then import it by using @import
-1

This is valid CSS:

p.text-red { color: red; }

9 Comments

that forces to add the class to all the needed html tags contrary to his question
Not contrary at all - the OP states "I want to apply text-red class to all paragraphs:" and again "all "p" elements"
correct my fault
Thanks - pls remove your downvote ;-)
Fair enough. In my opinion, p { .text-red } is an attempt to apply .text-red styles to all <p> elements, without explicitly defining those styles for <p> elements. It seems the OP wants to avoid adding the class to every <p> element because it is "redundant". I could be wrong, of course.
|
-2

Referring you to Child combinator:

https://developer.mozilla.org/en-US/docs/Web/CSS/Child_selectors

example

.text-red > p {
  ...
}

this selects all the p children of .text-red class

9 Comments

So you mean to place the class on the container? Not seems really related to the question, but in some situations it can be useful.
Some down-votes need to be explained, at least to learn something
@Qwertiy he mentioned that he doesn't want to specify on each html element. that's the reason for the approach
The OP does not seem to be targeting <p> elements as children of .text-red.
@AlexMounir, he asks about smth like @include or @extends from css preprocessors. You don't answer that question. I haven't voted on your answer, but I think downvotes are related to that fact.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.