Lucas Phillips
Lucas Phillips

Reputation: 645

CSS class templates?

Is there any way to create a "template" class in CSS that can be used in multiple classes? For example:

.tile {
    position: absolute;
    background: #ededed;
    width: 100px;
    padding: 10px;
    margin: 5px;
}

.tileA {
    class: tile;
    height: 100px;
}

.tileB {
    class: tile;
    height: 200px;
}

Upvotes: 1

Views: 3170

Answers (7)

ScottS
ScottS

Reputation: 72261

Attribute Selector Could Work Well Here

This would apply the css to all the .tile classes looking at the class attribute:

[class^='tile'], /* selects if any "tile" class is the first class */
[class*=' tile'] /* selects if any later class starting with "tile" */
{
    position: absolute;
    background: #ededed;
    width: 100px;
    padding: 10px;
    margin: 5px;
}

.tileA {
    height: 100px;
}

.tileB {
    height: 200px;
}

Upvotes: 0

chipcullen
chipcullen

Reputation: 6960

Not in the classical programming sense, no. At least, not with vanilla CSS.

There are a couple ways to do something similar, though:

  • Use multiple classes on the elements, eg class="tile tileA"
  • Use a preprocessor (such as SASS) and use an @extend directive:

%tile { 
    ... 
 }
.tileA  {
   @extend %tile;
   height: 100px;
}
.tileB {
   @extend %tile;
   height:200px;
}

Upvotes: 1

Sadeghbayan
Sadeghbayan

Reputation: 1163

it would be possible with COMPASS and SASS

That's what Sass for , try it

Upvotes: 0

codingrose
codingrose

Reputation: 15699

Use classes efficiently. You can give multiple classes to elements.

You can use pre-processors like LESS and SASS.

Try:

HTML:

<element class="tile tileA"></element>
<element class="tile tileB"></element>

CSS:

.tile {
    position: absolute;
    background: #ededed;
    width: 100px;
    padding: 10px;
    margin: 5px;
}

.tileA {
    height: 100px;
}

.tileB {
    height: 200px;
}

Upvotes: 5

talegna
talegna

Reputation: 2403

You can't inherit as such using CSS but as previously demonstrated you can assign the "sub-classes" to the base class definition See: CSS Inheritance

There is also quite a good article regarding CSS and inheritance targeted at Object Orientated programmers: http://dorward.me.uk/www/css/inheritance/

There are third party tools which can do something similar (SASS I believe is quite popular) but basically pure CSS does not support inheritence.

Upvotes: 1

jksloan
jksloan

Reputation: 184

Check out CSS pre-processors like SASS and LESS. I know SASS does what you're looking for.

Upvotes: 1

Brewal
Brewal

Reputation: 8189

Just do this :

.tile, .tileA, .tileB {
    position: absolute;
    background: #ededed;
    width: 100px;
    padding: 10px;
    margin: 5px;
}

.tileA {
    height: 100px;
}

.tileB {
    height: 200px;
}

Upvotes: 4

Related Questions