2

Possible Duplicate:
Inherit CSS class

Does CSS support inheritance ?

Assuming we have:

.base
{
}

.class1 :base
{
}

.class2 :base
{
}

How can I make class1 and class2 contain all styles which exist in base?

Community
  • 1
  • 1
Homam
  • 23,263
  • 32
  • 111
  • 187
  • No, see [Inherit CSS class](http://stackoverflow.com/questions/5417356/inherit-css-class) – deceze Mar 24 '11 at 13:07
  • 1
    Best not to confuse the meaning of the word "class" between CSS and OOP. They're very different. – David Mar 24 '11 at 13:20

4 Answers4

3

CSS doesn't support inheritance in the class sense of the word, but is based on specifity and order. If you define a common set of properties for classes class1 and class2, and then specialize as needed.

.class1, .class2
{
    font-size:1.1em;
}

.class1
{
    color:red;
}

.class2
{
    color:green;
}
Xhalent
  • 3,914
  • 22
  • 21
2

No. What you could do is use the base class, and have another class1, and class2 with the styles you need, than add both classes to the element. For example:

.base
{
color: Black;
font-size: 12pt;
}

.class1
{
font-weight: bold;
color: Blue;
}
<div class="base">This will be black, 12pt.</div>
<div class="base class1">This will be blue, 12pt, bold.</div>
rucsi
  • 516
  • 2
  • 7
1

CSS does support inheritance. If you html tags are laid out like:

<div class="base">
    ...
    <div class="class1>
        ...
    </div>
    <div class="class2">
        ...
    </div>
</div>

Class1 and Class2 will inherit whatever styles you assign to Base as long they are not explicitly overridden in your style sheet.

.base {
    font-size: 12pt;    // all child elements get this font size if another font-size is not specified
}

Check out w3.org for more.

Mike D
  • 4,938
  • 6
  • 43
  • 99
1

No, but there are some tools (like SASS) that you can use to "compile" CSS. An example:

SASS:

.error {
  border: 1px #f00;
  background: #fdd;
}
.error.intrusion {
  font-size: 1.3em;
  font-weight: bold;
}

.badError {
  @extend .error;
  border-width: 3px;
}

, which "compiles" to:

.error, .badError {
  border: 1px #f00;
  background: #fdd;
}

.error.intrusion,
.badError.intrusion {
  font-size: 1.3em;
  font-weight: bold;
}

.badError {
  border-width: 3px;
}
bhamby
  • 15,112
  • 1
  • 45
  • 66