WalterKPhillips
WalterKPhillips

Reputation: 31

How to create a CSS class that includes other class to prevent repeating multiple css class?

I have a list of css whose combination gives me the desired outcome. However, I find myself repeating this lists. e.g.

<div id="div1"><h4 class="muted-text text-center cursive text"> Text 1</h4></div>
<div id="div2"><h4 class="muted-text text-center cursive text"> Text 2 </h4></div>
<div id="div3"><h4 class="muted-text text-center cursive text"> Text 3</h4></div>
<div id="div4"><h4 class="muted-text text-center cursive text"> Text 4</h4></div>

I want to be able to do it as such:

<div id="div1"><h4 class="portfolio-title"> Text 1</h4></div>
<div id="div2"><h4 class="portfolio-title"> Text 2</h4></div>
<div id="div3"><h4 class="portfolio-title"> Text 3</h4></div>
<div id="div4"><h4 class="portfolio-title"> Text 4</h4></div>

I'm using a combination of bootstrap provided class (muted-text & text-center) as well as my own cursive-text which is also used elsewhere by itself.

How can I achieve what I need in the css file?

Thanks for your help.

Upvotes: 1

Views: 284

Answers (3)

Haensz
Haensz

Reputation: 127

This is very easy with plain old CSS. Just chain the selectors you need together.

.muted-text.text-center.cursive-text {color: red;}
h4.muted-text.text-center.cursive-text {color: blue;}

Or just add the desired styles under your new portfolio-title. Both are shown in this example - https://jsfiddle.net/7wt5eb9t/1/ - so it's just a matter of figuring out which way will save you time in your project.

And because these are more specific than the CSS rules that apply to just one class, they will take precedence regardless of whether they are listed before or after the basic CSS rules such as ".muted-text" or ".text-center".

Upvotes: 0

Kyle Alwyn
Kyle Alwyn

Reputation: 71

Just make your own class.

.portfolio-title {
  color: #dddddd;
  text-align: center;
  font-family: cursive;
}

Or use SASS. You'd probably want to use a placeholder here, if you will use this base class repeatedly

%title {
  color: #dddddd;
  text-align: center;
  font-family: cursive;
}

.portfolio-title {
  @extend %title
}

.other-class {
  @extend %title
}

The output would be something like:

.portfolio-title, .other-class {
  color: #dddddd;
  text-align: center;
  font-family: cursive;
}

Upvotes: 2

benjarwar
benjarwar

Reputation: 1804

Try SASS. You can create a mixin, extend a class, or include one class in another.

Upvotes: 0

Related Questions