当我看到网站的初始代码和示例时,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" />

当前回答

除了其他答案....国际化。

根据内容语言的不同,通常需要调整元素的样式。

一个明显的例子就是从右向左的语言。

假设你使用你的代码:

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

现在假设你想让你的网站支持rtl语言——你需要:

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

现在,如果你想同时支持两种语言,没有办法用内联样式来赋值给float。

在CSS中,lang属性很容易解决这个问题

所以你可以这样做:

img {
  float:right;
}
html[lang="he"] img { /* Hebrew. or.. lang="ar" for Arabic etc */
  float:left;
}

Demo

其他回答

Code how you like to code, but if you are passing it on to someone else it is best to use what everyone else does. There are reasons for CSS, then there are reasons for inline. I use both, because it is just easier for me. Using CSS is wonderful when you have a lot of the same repetition. However, when you have a bunch of different elements with different properties then that becomes a problem. One instance for me is when I am positioning elements on a page. Each element as a different top and left property. If I put that all in a CSS that would really annoy the mess out of me going between the html and css page. So CSS is great when you want everything to have the same font, color, hover effect, etc. But when everything has a different position adding a CSS instance for each element can really be a pain. That is just my opinion though. CSS really has great relevance in larger applications when your having to dig through code. Use Mozilla web developer plugin and it will help you find the elements IDs and Classes.

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

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

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>

即使你只在这个例子中使用了一次样式,你仍然混合了CONTENT和DESIGN。查找“关注点分离”。