开发者

CSS: how to add a style to everything, unless it is defined

If I add a style like:

* {
  font-size: 14px;
}

and later I define for an element:

#开发者_高级运维myElement {
  font-size: 18px;
}

The fist one will override the second one.

Is there a way to define the first one, such as the second one will override it, and the 14px size will be applied to all the elements that don't define a size?

(I would like alternatives to the use of classes)


The element #myElement will override the first rule as it is more specific. If #myElement has children then the children will match the global selector. Try setting the rule on body.


Use !important

#myElement {
  font-size: 18px !important;
}

It's worth noting that in your example if you specifcally set a style on that element, be it a class or id, it will inherit properties but any specific styles it will overwrite. So doing the above is pretty pointless. This can be demostrated like so:

<style type="text/css">
    * {
        font-size: 60px;
    }

    #blah2 {
        font-size: 14px;
    }
</style>

<span id="blah1">i'm default size</span>
<br/>
<span id="blah2">i'm specially 14px</span>

fiddle: http://jsfiddle.net/garreh/3YuLD/


No, the first one will not override the second one. A selector with an id is more specific than a selector with an element, so the second will override the first one.

To override a rule you just have to make a rule that is more specific. Just count the number of id, class and element specifiers in the selector, where id is most specific.

You can read more about selector specificity here:
css.maxdesign.com.au/selectutorial/advanced_conflict.htm


The second rule should override the first one. Make sure your element has id="myElement". Use an inspector (such as Firebug or Chrome's Web Dev Tools) to see what styles are applied to your element an which are overridden.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜