Does the order of css stylesheet definitions matter?

核能气质少年 提交于 2019-12-21 03:19:25

问题


I have several stylesheets. The first one is a stylesheet with some styles that I would like to use as defaults. Depending on several factors, the code being used to generate the page may include some stylesheets with values that should override the defaults.

If I use this, can I trust that the values in the default stylesheet will be overridden by the values from the other stylesheet? I am using class selectors and will override values when the names match.

<link href="defaults.css" rel="stylesheet" type="text/css"/> 
<link href="valuestooverridedefaults.css" rel="stylesheet" type="text/css"/> 

This needs to work on all browsers, including mobile. I'd like to avoid having to use "!important", if possible.

Thanks!


回答1:


There is a defined cascade in which the styles are sorted and applied. When declarations have the same importance (weight), origin and specifity then the latter declaration wins. Most answers cover importance and specifity here but not origin.

Here are some very good slides about CSS Cascades.




回答2:


If the selectors are identical, the last loaded takes precedence, just as if you declared the same class twice in the same stylesheet.




回答3:


If you have defined style for a selector in more than one css file, the style from last loaded CSS file will be taken




回答4:


If I use this, can I trust that the values in the default stylesheet will be overridden by the values from the other stylesheet? I am using class selectors and will override values when the names match.

The answer is "yes", as you noted, when the selectors on the second sheet are identical to the first.

The use of !important will be the exception, so avoid it, as you also noted.




回答5:


Yes, that is how stylesheets work. The last one wins.

Just be sure the specificity of the default style sheet isn't greater than your override. And yes, avoid !important if you can. It's just silly.




回答6:


yep - the clue is on the name 'cascading' stylesheets. So an inline style will overwrite an style that is defined in the head and a style in the head will overwrite a style in a style sheet. The last style sheet load could overwrite the styles in the previous one loaded. If you use something like firebug or the inspector in chrome it will show you where each style has come from or what it has overidden.




回答7:


The simple answer is yes. Any styles re-declared further down the pages will overwrite the classes declared earlier on in the page load.

For this to work the second declaration of the class must be in the inheritance.

Classes like .content{} and .body .content{} may behave differently when inheriting styles.



来源:https://stackoverflow.com/questions/9231614/does-the-order-of-css-stylesheet-definitions-matter

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!