内联 CSS 有什么不好? [英] What's so bad about in-line CSS?

查看:32
本文介绍了内联 CSS 有什么不好?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我看到网站入门代码和示例时,CSS 总是在一个单独的文件中,命名为main.css"、default.css"或Site.css".然而,当我编写一个页面时,我经常想将 CSS 与 DOM 元素放在一起,例如通过在图像上设置float: right".我觉得这是糟糕的编码",因为在示例中很少这样做.

我明白,如果样式将应用于多个对象,明智的做法是遵循不要重复自己"(DRY)并将其分配给每个元素引用的 CSS 类.但是,如果我不想在另一个元素上重复 CSS,为什么不在我编写 HTML 时内嵌 CSS?

问题:使用内联 CSS 是否被认为是不好的,即使它只会用于该元素?如果是,为什么?

示例(这很糟糕吗?):

解决方案

当您想让网站看起来不同时,必须更改 100 行代码.这可能不适用于您的示例,但是如果您将内联 css 用于

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

如果页眉是在单个样式表中定义的,因此如果您想更改页眉在整个站点中的显示方式,只需在一处更改 css.

但是,我将是一个异端,并说在您的示例中,我认为没有问题.您的目标是单个图像的行为,它可能必须在单个页面上看起来正确,因此将实际的 css 放在样式表中可能会过大.

When I see website starter code and examples, the CSS is always in a separate file, named something like "main.css", "default.css", or "Site.css". However, when I'm coding up a page, I'm often tempted to throw the CSS in-line with a DOM element, such as by setting "float: right" on an image. I get the feeling that this is "bad coding", since it's so rarely done in examples.

I understand that if the style will be applied to multiple objects, it's wise to follow "Don't Repeat Yourself" (DRY) and assign it to a CSS class to be referenced by each element. However, if I won't be repeating the CSS on another element, why not in-line the CSS as I write the HTML?

The question: Is using in-line CSS considered bad, even if it will only be used on that element? If so, why?

Example (is this bad?):

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

解决方案

Having to change 100 lines of code when you want to make the site look different. That may not apply in your example, but if you're using inline css for things like

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

on each page to denote a page header, it would be a lot easier to maintain as

<div class="pageheader">  

if the pageheader is defined in a single stylesheet so that if you want to change how a page header looks across the entire site, you change the css in one place.

However, I'll be a heretic and say that in your example, I see no problem. You're targeting the behavior of a single image, which probably has to look right on a single page, so putting the actual css in a stylesheet would probably be overkill.

这篇关于内联 CSS 有什么不好?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆