开发者

Does CSS support inheritance [duplicate]

This question already has answers here: 开发者_运维问答 Closed 11 years ago.

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?


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


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>


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.


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜