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

当前回答

当你想让网站看起来不一样时,不得不修改100行代码。这可能不适用于你的例子,但如果你使用内联css的事情

<div style ="font-size:larger; text-align:center; font-weight:bold">

在每个页面上表示一个页眉,这样维护起来会容易得多

<div class="pageheader">  

如果pageheader定义在一个单独的样式表中,那么如果你想改变整个站点的页面header的外观,你只需在一个地方更改CSS。

然而,我要说的是,在你的例子中,我认为没有问题。您针对的是单个图像的行为,它可能必须在单个页面上显示正确,因此将实际的css放在样式表中可能会过度。

其他回答

当你想让网站看起来不一样时,不得不修改100行代码。这可能不适用于你的例子,但如果你使用内联css的事情

<div style ="font-size:larger; text-align:center; font-weight:bold">

在每个页面上表示一个页眉,这样维护起来会容易得多

<div class="pageheader">  

如果pageheader定义在一个单独的样式表中,那么如果你想改变整个站点的页面header的外观,你只需在一个地方更改CSS。

然而,我要说的是,在你的例子中,我认为没有问题。您针对的是单个图像的行为,它可能必须在单个页面上显示正确,因此将实际的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.

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

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