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?

2
  • No, see Inherit CSS class Commented Mar 24, 2011 at 13:07
  • 1
    Best not to confuse the meaning of the word "class" between CSS and OOP. They're very different. Commented Mar 24, 2011 at 13:20

4 Answers 4

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;
}
Sign up to request clarification or add additional context in comments.

Comments

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>

Comments

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.

Comments

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;
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.