当我看到网站的初始代码和示例时,CSS总是在一个单独的文件中,命名为“main.css”,“default.css”或“Site.css”。然而,当我编写一个页面时,我经常试图将CSS与DOM元素放在一起,例如在图像上设置“float: right”。我觉得这是“糟糕的编码”,因为在示例中很少这样做。

我明白,如果样式将应用于多个对象,明智的做法是遵循“不要重复自己”(Don't Repeat Yourself, DRY),并将其分配给每个元素引用的CSS类。然而,如果我不会在另一个元素上重复CSS,为什么不内联CSS,因为我写HTML?

问题是:使用内联CSS被认为是不好的,即使它只用于该元素?如果有,为什么?

例子(这样不好吗?)

<img src="myimage.gif" style="float:right" />

当前回答

Personally, I think the hatred of inline css is just ridiculous. Hardcore cult behaviour, people just sheepishly repeat "Separation of concerns!". Yes, there are times where if there is a repeating element and you will need repeated styling to use a class targeted from a CSS file, but most of the time it improves speed of development and CLARITY OF CODE to put the style inline, it's great if I can look at the code and see that there is a custom margin height, it helps me picture the HTML document as a whole, instead of some named class that gives me little insight into which styles will be applied.

所以在这里我要做一个逆向的人,我要说内联css是伟大的,那些对你使用它大喊大叫的人只是在遵循他们被告知的东西,而实际上并没有给予任何原始的、公正的考虑。

其他回答

使用内联CSS更难维护。

对于您想要更改的每个属性,使用内联CSS要求您查找相应的HTML代码,而不是只在定义清晰且结构良好的CSS文件中查找。

使用内联样式违反了关注点分离原则,因为您实际上是在同一个源文件中混合了标记和样式。在大多数情况下,它也违反了DRY(不要重复自己)原则,因为它们只适用于单个元素,而一个类可以应用于其中的几个元素(甚至可以通过CSS规则的魔力进行扩展!)

此外,如果站点包含脚本,明智地使用类是有益的。例如,一些流行的JavaScript库(如JQuery)严重依赖类作为选择器。

最后,使用类可以增加DOM的清晰度,因为可以有效地使用描述符告诉您其中给定节点是哪种元素。例如:

<div class="header-row">It's a row!</div>

表达能力比:

<div style="height: 80px; width: 100%;">It's...something?</div>

使用不同的css文件的好处是

易于维护您的html页面 更改外观和感觉将很容易,您可以在您的页面上支持许多主题。 您的css文件将缓存在浏览器端。因此,你将贡献一点互联网流量,不加载一些kbs的数据,每次一个页面刷新或用户导航你的网站。

除了其他答案,另一个问题是它违反了MDN https://infosec.mozilla.org/guidelines/web_security#content-security-policy推荐的内容安全政策

他们使用的理由是内联javascript是有害的,XSS等等,但这并不能证明为什么内联样式也应该被禁用。也许有人会评论其中的原因,但在此之前,我将只依赖于对权威的呼吁并声明:避免内联样式是安全的最佳实践。

尽管我完全同意上面给出的所有答案,在一个单独的文件中编写CSS从代码可重用性、可维护性和更好的关注点分离来看总是更好的,但在许多情况下,人们更喜欢在生产代码中使用内联CSS

The external CSS file causes one extra HTTP call to browser and thus additional latency. Instead if the CSS is inserted inline then browser can start parsing it right away. Especially over SSL HTTP calls are more costly and adds up additional latency to the page. There are many tools available that helps to generate static HTML pages (or page snippet) by inserting external CSS files as inline code. These tools are used at the Build and Release phase where the production binary is generated. This way we get all the advantages of external CSS and also the page becomes faster.