当我看到网站的初始代码和示例时,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。如果您编写了一个合适的级联样式表,而您的属性没有正确应用,这会让您非常头疼。

它还在语义上损害了应用程序:CSS是关于将表示与标记分离的。当您将两者纠缠在一起时,事情就变得更加难以理解和维护。这与在服务器端将数据库代码与控制器代码分离的原理类似。

最后,假设您有20个这样的图像标记。当你决定它们应该向左浮动时会发生什么?

我认为,即使您希望对一个元素具有某种样式,也必须考虑到可能希望对不同页面上的同一元素应用相同样式的可能性。

有一天,有人可能会要求对每页上的同一元素进行更多的风格更改。如果您在外部CSS文件中定义了样式,那么您只需在那里进行更改,并且它将反映在所有页面的相同元素中,从而为您省去了麻烦。: -)

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的全部意义在于将内容与其表示分开。所以在你的例子中,你把内容和表现形式混在一起了,这可能是“有害的”。

根据AMP HTML规范,为了性能目的,有必要将CSS放在HTML文件中(而不是外部样式表)。这并不意味着内联CSS,但它们确实没有指定外部样式表。

这样一个服务系统可能做的优化的不完整列表是: 将图像引用替换为符合查看器视口大小的图像。 内联图像在折页上方可见。 内联CSS变量。 预加载扩展组件。 精简HTML和CSS。