Cowgirl
Cowgirl

Reputation: 1494

CSS change a single element of one class without using a different class name

I was wondering if there is way to do this.

I want to change only a single property of a specific CSS class, without having it to copy it again and assigning a different class name.

So, if I have this class

<div class="example">I am a red font with properties </div>

It's CSS

.example {
font-size:2em;
font-color:red;
padding:2%;
display:inline;
//other several properties }

Now, I want to use the example class in my other div, but I JUST want the font to be green. I don't want to copy the same property and just assign a different class name,

<div class="example2">I am a green font with properties </div>

Again the example2 will be the same as example, but only the font color will change

It's CSS

.example2 {
 font-size:2em;
 font-color:green;
 padding:2%;
 display:inline;
 //other several properties same as example class

Is there a way to import the CSS property without having it to copy it and rename it? Something like

<div class="example" onlychange="font-color:green">
           I am a green font with properties </div>

Any techniques to achieve something like the onlychange attribute?

Upvotes: 3

Views: 21038

Answers (2)

Lab
Lab

Reputation: 1063

If you are sure that placement of DIV elements will remain same, then, you can try nth-child property. e.g. https://www.w3schools.com/cssref/sel_nth-child.asp

    <div class="example2">I am a red font with properties </div>
    <div class="example2">I am a green font with properties </div>
    <div class="example2">I am a red font with properties </div>

    Your style for that specific "example2" should be :
    <style>
    div.example2:nth-child(2){background-color:green;}
    </style>

Example is with 'background color', you can set 'color' property as well.

Upvotes: 1

Naren Murali
Naren Murali

Reputation: 57071

Here are two ways. First is add another class and change that one property alone, the second class property will replace the previous class property if its present in both.

Second approach will be to just write it as an inline style. No need for the extra class!

.example {
  font-size: 2em;
  color: red;
  padding: 2%;
  display: inline;
}

.green {
  color: green;
}
<span class="example green">test</span>

<span class="example" style="color:green;">test</span>

Upvotes: 9

Related Questions