当我看到网站的初始代码和示例时,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放在一个文本文件中,用php动态加载它,并将它输出到文档头中。在<head>部分包括:
<head> ...
<?php
$codestring = file_get_contents("styles/style1.txt");
echo "<style>" . $codestring . "</style>";
?>
... </head>
将所需的css放在styles/style1.txt中,它将在文档的<head>部分中输出。这样,你就可以使用样式模板style1.txt,它可以被任何和所有页面共享,允许站点范围内的样式更改仅通过一个文件进行。此外,这种方法不需要浏览器从服务器请求单独的css文件(从而最小化检索/呈现时间),因为所有内容都是由php一次性交付的。
实现此功能后,可以在需要的地方手动编码单独的一次性样式。
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是伟大的,那些对你使用它大喊大叫的人只是在遵循他们被告知的东西,而实际上并没有给予任何原始的、公正的考虑。