开发者

Defining a 'compound' style in CSS

Is it possible to define a CSS style such that it includes another by default?

For example, take the following classes:

.rounded{
  -webkit-border-radius:5px;
  -moz-border-radius:5px;
  border-radius:5px;
}
.box{
  height:200px;
  width:400px;
}

Instead of writing <div class开发者_如何学编程="rounded box"> everywhere on the site (which would probably lead to less consistency and would almost definitely lead to long strings of classes in the html), can I define .box to automatically include .rounded?

This has implications for redundancy in the CSS and CSS tags - I'd rather not have to specify border-radii each time I come to an element in a new situation or context that could, for example, incorporate .big_rounded, .med_rounded or .small_rounded.


You could do:

.box, .rounded {
  -webkit-border-radius:5px;
  -moz-border-radius:5px;
  border-radius:5px;
}

.box {
  height:200px;
  width:400px;
}


A simple solution is given by Melv, however CSS doesn't support true inheritance.

Alternatively, there are tools/frameworks that extend CSS syntax. Two popular ones I know of are LESS and SASS. Among their many benefits are "mixins" that allow for CSS inheritance. You use framework's syntax to indicate inheritance and the tools generate the CSS.

LESS example:

.rounded{
  -webkit-border-radius:5px;
  -moz-border-radius:5px;
  border-radius:5px;
}
.box{
  height:200px;
  width:400px;
  .rounded; /* This is a mixin */
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜