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

当前回答

内联CSS总是优先于任何链接样式表CSS。如果您编写了一个合适的级联样式表,而您的属性没有正确应用,这会让您非常头疼。

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

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

其他回答

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

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

这只适用于手写代码。如果您生成代码,我认为可以在这里使用内联样式,特别是在元素和控件需要特殊处理的情况下。

对于手写代码来说,DRY是一个很好的概念,但对于机器生成的代码,我选择了“得墨忒耳定律”:“属于一起的东西必须保持在一起”。操作生成Style标签的代码比在不同的“远程”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更难维护。

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

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.