将 <body> 中的 <style> 标签与其他 HTML 一起使用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2830296/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 03:05:33  来源:igfitidea点击:

Using <style> tags in the <body> with other HTML

htmlcss

提问by Gagan

<html>
  <body>
    <style type="text/css">
      p.first {color:blue}
      p.second {color:green}
    </style>

    <p class="first">Hello World</p>
    <p class="second">Hello World</p>

    <style type="text/css">
      p.first {color:green}
      p.second {color:blue}
    </style>

    <p class="first">Hello World</p>
    <p class="second">Hello World</p>
  </body>
</html>

How is a browser supposed to render css which is non contiguous? Is it supposed to generate some data structure using all the css styles on a page and use that for rendering?

浏览器应该如何呈现不连续的 css?是否应该使用页面上的所有 css 样式生成一些数据结构并将其用于渲染?

Or does it render using style information in the order it sees?

或者它是否按照它看到的顺序使用样式信息进行渲染?

回答by Charles Salvia

As others have already mentioned, HTML 4 requires the <style>tag to be placed in the <head>section (even though most browsers allow <style>tags within the body).

正如其他人已经提到的那样,HTML 4 要求将<style>标记放置在<head>部分中(尽管大多数浏览器允许在 中添加<style>标记body)。

However, HTML 5 includes the scopedattribute(see update below), which allows you to create style sheets that are scoped within the parent element of the <style>tag. This also enables you to place <style>tags within the <body>element:

但是,HTML 5 包含scoped属性(请参阅下面的更新),它允许您创建范围在<style>标记的父元素内的样式表。这也使您可以<style><body>元素中放置标签:

<!DOCTYPE html>
<html>
<head></head>
<body>

<div id="scoped-content">
    <style type="text/css" scoped>
        h1 { color: red; } 
    </style>

    <h1>Hello</h1>
</div>

    <h1>
      World
    </h1>

</body>
</html>

If you render the above code in an HTML-5 enabled browser that supports scoped, you will see the limited scope of the style sheet.

如果您在支持 的支持 HTML-5 的浏览器中呈现上述代码scoped,您将看到样式表的范围有限。

There's just one majorcaveat...

只有一个主要警告...

At the time I'm writing this answer (May, 2013) almost no mainstream browser currently supports the scopedattribute. (Although apparently developer builds of Chromiumsupport it.)

在我写这个答案时(2013 年 5 月),目前几乎没有主流浏览器支持该scoped属性。(尽管显然Chromium 的开发人员版本支持它。)

HOWEVER, there is an interesting implication of the scopedattribute that pertains to this question. It means that future browsers are mandated via the standard to allow <style>elements within the <body>(as long as the <style>elements are scoped.)

但是,scoped与此问题相关的属性有一个有趣的含义。这意味着未来的浏览器通过标准被要求允许<style>元素在<body>(只要<style>元素是范围内的。)

So, given that:

所以,鉴于:

  • Almost every existing browser currently ignores the scopedattribute
  • Almost every existing browser currently allows <style>tags within the <body>
  • Future implementations will be required to allow (scoped) <style>tags within the <body>
  • 目前几乎所有现有浏览器都忽略了该scoped属性
  • 几乎所有现有的浏览器目前都允许<style><body>
  • 未来的实现将需要<style><body>

...then there is literally no harm* in placing <style>tags within the body, as long as you future proof them with a scopedattribute. The only problem is that current browsers won't actually limit the scopeof the stylesheet - they'll apply it to the whole document. But the point is that, for all practical purposes, you caninclude <style>tags within the <body>provided that you:

...那么在正文中放置标签实际上没有害处* <style>,只要您将来使用scoped属性证明它们即可。唯一的问题是当前的浏览器实际上不会限制样式表的范围——它们会将其应用于整个文档。但关键是,出于所有实际目的,您可以<style>在以下<body>条件中包含标签:

  • Future-proof your HTML by including the scopedattribute
  • Understand that as of now, the stylesheet within the <body>will not actually be scoped (because no mainstream browser support exists yet)
  • 通过包含该scoped属性使您的 HTML 面向未来
  • 了解截至目前, 中的样式表<body>实际上不会被限定(因为尚不存在主流浏览器支持)


* except of course, for pissing off HTML validators...


* 当然,除了为了激怒 HTML 验证器...



Finally, regarding the common (but subjective) claim that embedding CSS within HTML is poor practice, it should be noted that the whole pointof the scopedattribute is to accommodate typical modern development frameworks that allow developers to import chunks of HTML as modules or syndicated content. It is very convenient to have embedded CSS that onlyapplies to a particular chunk of HTML, in order to develop encapsulated, modular components with specific stylings.

最后,关于在 HTML 中嵌入 CSS 是一种糟糕的做法的普遍(但主观)的说法,应该注意的是,该属性的全部意义scoped在于适应典型的现代开发框架,允许开发人员将 HTML 块作为模块或联合内容导入. 嵌入适用于特定 HTML 块的CSS 非常方便,以便开发具有特定样式的封装、模块化组件。



Update as of Feb 2019, according to the Mozilla documentation, the scopedattribute is deprecated. Chrome stopped supporting it in version 36 (2014) and Firefox in version 62 (2018). In both cases, the feature had to be explicitly enabled by the user in the browsers' settings. No other major browser ever supported it.

截至 2019 年 2 月更新,根据Mozilla 文档,该scoped属性已弃用。Chrome 在版本 36 (2014) 和 Firefox 版本 62 (2018) 中停止支持它。在这两种情况下,用户都必须在浏览器的设置中明确启用该功能。没有其他主要浏览器支持它。

回答by Sz.

BREAKING BAD NEWSfor "style in body" lovers: W3C has recently lost the HTML waragainst WHATWG, whose versionless HTML "Living Standard" has now becomethe official one, which, alas, does notallowSTYLEin the BODY. The short-lived happy days are over. ;) The W3C validatoralso works by the WHATWG specs now. (Thanks @FrankConijn for the heads-up!)

坏消息的“风格体”爱好者:W3C最近失去了HTMLWar对WHATWG,其versionless HTML“生活标准”现在已经成为了一个官方的,这,唉,不会允许STYLEBODY。短暂的快乐日子结束了。;) W3C 验证器现在也适用于 WHATWG 规范。(感谢@FrankConijn 的提醒!)

(Note: this is the case "as of today", but since there's no versioning, links can become invalid at any moment without notice or control. Unless you're willing to link to its individual source commits at GitHub, you basically can no longer make stable references to the new official HTML standard, AFAIK. Please correct me if there's a canonical way of doing this properly.)

(注意:这是“截至今天”的情况,但由于没有版本控制,链接可能在没有通知或控制的情况下随时失效。除非您愿意链接到 GitHub 上的单个源提交,否则您基本上不能不再对新的官方HTML 标准AFAIK进行稳定引用。如果有正确的规范方法,请纠正我。)

OBSOLETED GOOD NEWS:

过时的好消息:

Yay, STYLEis finally valid in BODY, as of HTML5.2!(And scopedis gone, too.)

耶,STYLE终于在有效的BODY,作为HTML5.2的!scoped也不见了。)

From the W3C specs(relish the last line!):

来自W3C 规范喜欢最后一行!):

4.2.6. The style element

...

Contexts in which this element can be used:

Where metadata content is expected.

In a noscript element that is a child of a head element.

In the body, where flow content is expected.

4.2.6. 风格元素

...

可以使用此元素的上下文:

预期元数据内容的位置。

在作为 head 元素的子元素的 noscript 元素中。

在正文中,预期流内容的位置。



META SIDE-NOTE:

元侧注:

The mere fact that despite the damages of the "browser war" we still had to keep developing against two ridiculously competing"official" HTML "standards" (quotes for 1 standard + 1 standard < 1 standard) means that the "fallback to in-the-trenches common sense" approach to web development has never really ceased to apply.

尽管“浏览器War”造成了损害,但我们仍然不得不针对两个可笑的“官方”HTML“标准”(引述1 standard + 1 standard < 1 standard)继续开发这一事实意味着“退回到战壕中的常识”方法Web 开发从未真正停止应用。

This may finally change now, but citing the conventional wisdom: web authors/developers and thus, in turn, browsers should ultimately decide what should (and shouldn't) be in the specifications, when there's no good reason against what's already been done in reality. And most browsers have long supported STYLEin BODY(in one way or another; see e.g. the scopedattr.), despite its inherent performance (and possibly other) penalties (which weshould decide to pay or not, not the specs.). So, for one, I'll keep betting on them, and not going to give up hope. ;) If WHATWG has the same respect for reality/authors as they claim, they may just end up doing here what the W3C did.

现在这可能最终会改变,但引用传统智慧:网络作者/开发人员以及浏览器最终应该决定什么应该(和不应该)在规范中,当没有充分的理由反对已经完成的事情时现实。和大多数浏览器长期以来一直支持STYLEBODY(以这种或那种方式;见例如scoped,attr)使用(其中,尽管其固有的性能(可能还有其他)的处罚我们。应该决定工资与否,不是规格)。所以,一方面,我会继续押注他们,不会放弃希望。;) 如果 WHATWG 像他们声称的那样尊重现实/作者,他们可能最终会在这里做 W3C 所做的事情。

回答by Timberline

When I see that the big-site Content Management Systems routinely put some <style> elements (some, not all) close to the content that relies on those classes, I conclude that the horse is out of the barn.

当我看到大型站点内容管理系统经常将一些 <style> 元素(一些,而不是全部)靠近依赖于这些类的内容时,我得出结论,这匹马已经离开了谷仓。

Go look at page sources from cnn.com, nytimes.com, huffingtonpost.com, your nearest big-city newspaper, etc. All of them do this.

去看看来自 cnn.com、nytimes.com、huffingtonpost.com、离你最近的大城市报纸等的页面资源。他们都这样做。

If there's a good reason to put an extra <style> section somewhere in the body -- for instance if you're include()ing diverse and independent page elements in real time and each has an embedded <style> of its own, and the organization will be cleaner, more modular, more understandable, and more maintainable -- I say just bite the bullet. Sure it would be better if we could have "local" style with restricted scope, like local variables, but you go to work with the HTML you have, not the HTML you might want or wish to have at a later time.

如果有充分的理由在正文中的某处放置一个额外的 <style> 部分 - 例如,如果您实时包含()不同且独立的页面元素,并且每个元素都有自己的嵌入式 <style> ,并且组织将更干净、更模块化、更易于理解、更易于维护——我说只是咬紧牙关。当然,如果我们可以拥有具有受限范围的“本地”样式(例如局部变量)会更好,但是您可以使用您拥有的 HTML,而不是您以后可能想要或希望拥有的 HTML。

Of course there are potential drawbacks and good (if not always compelling) reasons to follow the orthodoxy, as others have elaborated. But to me it looks more and more like thoughtful use of <style> in <body> has already gone mainstream.

当然,正如其他人所阐述的那样,遵循正统有潜在的缺点和好的(如果不总是令人信服的)理由。但在我看来,在 <body> 中精心使用 <style> 已经越来越成为主流。

回答by nico

Not valid HTML, anyway pretty much every browser seems to consider just the second instance.

无效的 HTML,无论如何几乎每个浏览器似乎都只考虑第二个实例。

Tested under the last versions of FF and Google Chrome under Fedora, and FF, Opera, IE, and Chrome under XP.

在 Fedora 下的 FF 和 Google Chrome 的最新版本以及 XP 下的 FF、Opera、IE 和 Chrome 下测试。

回答by Pekka

I guess this will vary from browser to browser: The global display rules will probably be updated as the browser goes along through the code.

我想这会因浏览器而异:随着浏览器执行代码,全局显示规则可能会更新。

You can see such changes in the global display rules sometimes when an external style sheet is loaded with a delay. Something similar might happen here but in such short succession that it doesn't actually get rendered.

当外部样式表延迟加载时,您有时会在全局显示规则中看到此类更改。类似的事情可能会在这里发生,但在如此短的连续时间内实际上并没有被渲染。

It's not valid HTML anyway, so I'd say that it is a futile thing to think about. <style>tags belong in the headsection of the page.

无论如何,它都不是有效的 HTML,所以我想说这是一件徒劳的事情。<style>标签属于head页面的部分。

回答by Josh Stodola

The <style>tag belongs in the <head>section, separate from all the content.

<style>标签属于该<head>部分,与所有内容分开。

References: W3C Specsand W3Schools

参考资料:W3C 规范W3Schools

回答by NotMe

As others have said, this isn't valid html as the style tags belong in the head.

正如其他人所说,这不是有效的 html,因为样式标签属于头部。

However, most browsers dont' really enforce that validation. Instead, once the document is loaded then the styles are merged and applied. In this case the second set of styles will always override the first because they were the last definitions encountered.

但是,大多数浏览器并没有真正强制执行该验证。相反,一旦加载了文档,就会合并并应用样式。在这种情况下,第二组样式将始终覆盖第一组样式,因为它们是遇到的最后一个定义。

回答by Quentin

In your example, a browser isn't "supposed" to do anything. The HTML is invalid. Either error recovery is triggered, or the parser makes of it as it will.

在您的示例中,浏览器“不应该”执行任何操作。HTML 无效。要么触发错误恢复,要么解析器按照它的意愿进行处理。

In a valid instance, multiple stylesheets are just treated as appearing one after the other, the cascadeis calculated as normal.

在一个有效的实例中,多个样式表只是被视为一个接一个出现,级联计算正常。

回答by G. Bickham

Because this is HTML is not valid does not have any affect on the outcome ... it just means that the HTML does adhere to the standard (merely for organizational purposes). For the sake of being valid it could have been written this way:

因为这是无效的 HTML 对结果没有任何影响......它只是意味着 HTML 确实遵守标准(仅用于组织目的)。为了有效起见,它可以这样写:

<html>
<head>
<style type="text/css">
  p.first {color:blue}
  p.second {color:green}
</style>
</head>
<body>
<p class="first" style="color:green;">Hello World</p>
<p class="second" style="color:blue;">Hello World</p>

My guess is that the browser applies the last style it comes across.

我的猜测是浏览器应用了它遇到的最后一种样式。

回答by Igor Santos

I guess this may be an issue about limited contexts, e.g. WYIWYG editors on a web system used by not-programmers users, that limits the possibilities of follow the standards. Sometimes (like TinyMCE), it's a lib that puts your content/code inside a textareatag, that is rendered by the editor as a big divtag. And sometimes, it may be an old version of these editors.

我想这可能是关于有限上下文的问题,例如非程序员用户使用的 Web 系统上的 WYIWYG 编辑器,这限制了遵循标准的可能性。有时(如 TinyMCE),它是一个将您的内容/代码放在textarea标签中的库,该标签由编辑器呈现为一个大div标签。有时,它可能是这些编辑器的旧版本。

I'm supposing that:

我假设:

  1. these not-programmers usersdon't have an open channel with the system admins (or institution's webdevs), to ask for including some CSS rules at the system's stylesheets. Actually, it would be impractical for the admins (or webdevs), considering the number of requests in that sense that they would have.
  2. this system is legacy and still doesn't support newer versions of HTML.
  1. 这些非程序员用户没有与系统管理员(或机构的 webdevs)的开放渠道,要求在系统的stylesheets. 实际上,考虑到他们将拥有的请求数量,这对于管理员(或网络开发人员)来说是不切实际的。
  2. 该系统是旧系统,仍然不支持较新版本的 HTML。

In some cases, without use stylerules, it may be a very poor design experience. So, yes, these users need customization. Okay, but what would be the solutions, in this scenario? Considering the different ways to insert CSS in a htmlpage, I suppose these solutions:

在某些情况下,如果没有使用style规则,可能是非常糟糕的设计体验。所以,是的,这些用户需要定制。好的,但是在这种情况下,解决方案是什么?考虑到在html页面中插入 CSS 的不同方式,我想这些解决方案:



1st option: ask your sysadm

第一个选项:询问您的系统管理员

Ask to your system adm for including some CSS rules at the system's stylesheets. This will be an external or internal CSSsolution. As already said, it might be not possible.

要求您的系统管理员在系统的stylesheets. 这将是一个外部或内部 CSS解决方案。如前所述,这可能是不可能的。



2nd option: <link>on <body>

第二个选项:<link><body>

Use external style sheeton the bodytag, i.e., use of the linktag insidethe area you have access (that will be, on the site, inside the bodytag and not in the headtag). Some sources says this is okay, but "not a good practice", like MDN:

在标签上使用外部样式表body,即在您有权访问的区域使用link标签(即在网站上,在标签内,而不是在标签内)。一些消息来源说这没问题,但“不是一个好习惯”,比如MDNbodyhead

A <link>element can occur either in the <head>or <body>element, depending on whether it has a link type that is body-ok. For example, the stylesheetlink type is body-ok, and therefore <link rel="stylesheet">is permitted in the body. However, this isn't a good practice to follow; it makes more sense to separate your <link>elements from your body content, putting them in the <head>.

<link>元件可以在任一发生<head><body>元件,这取决于它是否有链路类型,它是身体-OK。例如,stylesheet链接类型是 body-ok,因此<link rel="stylesheet">在 body 中是允许的。然而,这不是一个好的做法。将<link>元素与正文内容分开,将它们放在<head>.

Some others, restrict it to the <head>section, like w3schools:

其他一些,将其限制在该<head>部分,例如w3schools

Note:This element goes only in the head section, but it can appear any number of times.

注意:此元素仅出现在 head 部分,但它可以出现任意次数。

Testing

测试

I tested it here (desktop environment, on a browser) and it works for me. Create a file foo.html:

我在这里测试了它(桌面环境,在浏览器上),它对我有用。创建一个文件foo.html

<!DOCTYPE html>
<html>
<head></head>
<body>
    <link href="bar.css" type="text/css" rel="stylesheet">
    <h1 class="test1">Hello</h1>
    <h1 class="test2">World</h1>
</body>
</html>

And then a CSS file, at the same directory, called bar.css:

然后是一个 CSS 文件,在同一目录下,名为bar.css

.test1 { 
    color: green;
};

Well, this will just looks possible if you have how upload an CSS file somewhere at the institution system. Maybe this would be the case.

好吧,如果您知道如何在机构系统的某处上传 CSS 文件,这看起来是可能的。也许情况就是这样。



3rd option: <style>on <body>

第三个选项:<style><body>

Use internet style sheeton the bodytag, i.e., use of the styletag inside the area you have access (that will be, on the site, inside the bodytag and not in the headtag). This is what Charles Salvia's and Sz's answers here are about. Choosing this option, consider their concerns.

在标签上使用Internet 样式表body,即style在您有权访问的区域内使用标签(即在网站上,在body标签内,而不是在head标签内)。这就是Charles SalviaSz在这里的回答。选择此选项,请考虑他们的担忧。



4th, 5th and 6th options: JS ways

第 4、5、6 选项:JS 方式

Alert These ones are related to modifying the <head>element of the page. Maybe this will notbe allowed by the institution's system administrators. So, it's recommended to ask them permission first.

Alert 这些与修改<head>页面元素有关。也许机构的系统管理员不会允许这样。因此,建议先征得他们的许可。

Okay, supposing permission granted, the strategy is access the <head>. How? JavaScript methods.

好的,假设授予权限,策略是访问<head>. 如何?JavaScript 方法。

4th option: new <link>on <head>

第四选项:新<link><head>

This is another version of the 2nd option. Use external style sheeton the <head>tag, i.e., use of the <link>element outsidethe area you have access (that will be, on the site, not inside the bodytag and yes inside the headtag). This solution complies with the recommendations of MDNand w3schools, as cited above, on 2nd option solution. A new Linkobjectwill be created.

这是第二个选项的另一个版本。在标签上使用外部样式表<head>,即在您有权访问的区域使用<link>元素(即,在网站上,不在标签内,是在标签内)。该解决方案符合MDNw3schools的建议,如上所述,作为第二个选项解决方案。将创建一个新对象bodyheadLink

To solve the matter through JS, there are many ways but at the following codelines I demonstrate one simple.

要通过 JS 解决这个问题,有很多方法,但在以下代码行中,我演示了一个简单的方法。

Testing

测试

I tested it here (desktop environment, on a browser) and it works for me. Create a file f.html:

我在这里测试了它(桌面环境,在浏览器上),它对我有用。创建一个文件f.html

<!DOCTYPE html>
<html>
<head></head>
<body>
    <h1 class="test1">Hello</h1>
    <h1 class="test2">World</h1>
    <script>
        // JS code here
    </script>
</body>
</html>

Inside the scripttag:

里面的script标签:

var newLink = document.createElement("link");
newLink.href = "bar.css";
newLink.rel = "stylesheet";
newLink.type = "text/css";
document.getElementsByTagName("head")[0].appendChild(newLink);

And then at the CSS file, at the same directory, called bar.css(as at the 2nd option):

然后在 CSS 文件中,在同一目录中,调用bar.css(如第二个选项):

.test1 { 
    color: green;
};

As I already said: this will just looks possible if you have how upload an CSS file somewhere at the institution system.

正如我已经说过的:如果您知道如何在机构系统的某处上传 CSS 文件,这看起来是可能的。

5th option: new <style>on <head>

5日选项:新<style><head>

Use new internal style sheeton the <head>tag, i.e., use of a new <style>element outsidethe area you have access (that will be, on the site, not inside the bodytag and yes inside the headtag). A new Styleobjectwill be created.

在标签上使用新的内部样式表<head>,即在您有权访问的区域使用新<style>元素(即在网站上,不在标签内,在标签内是)。将创建一个新对象bodyheadStyle

This is solved through JS. One simple way is demonstrated following.

这是通过JS解决的。下面演示一种简单的方法。

Testing

测试

I tested it here (desktop environment, on a browser) and it works for me. Create a file foobar.html:

我在这里测试了它(桌面环境,在浏览器上),它对我有用。创建一个文件foobar.html

<!DOCTYPE html>
<html>
<head></head>
<body>
    <h1 class="test1">Hello</h1>
    <h1 class="test2">World</h1>
    <script>
        // JS code here
    </script>
</body>
</html>

Inside the scripttag:

里面的script标签:

var newStyle = document.createElement("style");
newStyle.innerHTML = 
    "h1.test1 {"+
        "color: green;"+
    "}";
document.getElementsByTagName("head")[0].appendChild(newStyle);

6th option: using an existing <style>on <head>

第 6 个选项:使用现有<style><head>

Use an existing internal style sheeton the <head>tag, i.e., use of a <style>element outsidethe area you have access (that will be, on the site, not inside the bodytag and yes inside the headtag), if some exists. A new Styleobject will be created or a CSSStyleSheetobjectwill be used (in the code of the solution adopted here).

在标签上使用现有的内部样式表<head>,即,在您有权访问的区域使用<style>元素(即在站点上,不在标签内,并且在标签内),如果存在的话。将创建一个新对象或使用一个对象(在此处采用的解决方案的代码中)。bodyheadStyleCSSStyleSheet

This is at some point of view risky. First, because it may not exists some <style>object. Depending of the way you implement this solution, you may get undefinedreturn (the system may use external style sheet). Second, because you will be editing the system design author's work (authorship issues). Third, because it may not be allowed at your institution's IT politics of safety. So, do ask permission to do this (as at in other JS solutions).

这在某些方面是有风险的。 首先,因为它可能不存在某个<style>对象。根据您实施此解决方案的方式,您可能会得到undefined回报(系统可能使用外部样式表)。 其次,因为您将编辑系统设计作者的作品(作者身份问题)。 第三,因为您所在机构的 IT 安全政策可能不允许这样做。因此,请务必获得许可才能这样做(如在其他 JS 解决方案中一样)

Supposing, again, permission was granted:

假设再次获得许可:

You will need to consider some restrictions of the method available to this way: insertRule(). The solution proposed uses the default scenario, and a operation at the first stylesheet, if some exists.

您将需要考虑这种方式可用的方法的一些限制:insertRule(). 建议的解决方案使用默认方案,并在第一个操作(stylesheet如果存在)。

Testing

测试

I tested it here (desktop environment, on a browser) and it works for me. Create a file foo_bar.html:

我在这里测试了它(桌面环境,在浏览器上),它对我有用。创建一个文件foo_bar.html

<!DOCTYPE html>
<html>
  <head></head>
  <body>
    <h1 class="test1">Hello</h1>
    <h1 class="test2">World</h1>
    <script>
      // JS code here
    </script>
  </body>
</html>

Inside the scripttag:

里面的script标签:

function demoLoop(){ // remove this line
    var elmnt = document.getElementsByTagName("style");
    if (elmnt.length === 0) {
        // there isn't style objects, so it's more interesting create one
        var newStyle = document.createElement("style");
        newStyle.innerHTML =
            "h1.test1 {" +
                "color: green;" +
            "}";
        document.getElementsByTagName("head")[0].appendChild(newStyle);
    } else {
        // Using CSSStyleSheet interface
        var firstCSS = document.styleSheets[0];
        firstCSS.insertRule("h1.test2{color:blue;}"); // at this way (without index specified), will be like an Array unshift() method
    }
} // remove this too
demoLoop(); // remove this too
demoLoop(); // remove this too

Another approach to this solution it's using CSSStyleDeclarationobject (docs at w3schoolsand MDN). But it may not be interesting, considering the risk to override existing rules on the system's CSS.

该解决方案的另一种方法是使用CSSStyleDeclaration对象(w3schoolsMDN 上的文档)。但考虑到覆盖系统 CSS 上现有规则的风险,这可能并不有趣。



7th option: inline CSS

第 7 个选项:内联 CSS

Use inline CSS. This solve the problem, although depending of the page size (in code lines), the maintenance (by the author itself or other assigned person) of code can be very difficult.

使用内联 CSS。这解决了问题,尽管取决于页面大小(以代码行为单位),代码的维护(由作者自己或其他指定人员)可能非常困难。

But depending of the context of your role at the institution, or its web system security policies, this might be the unique available solution to you.

但是,根据您在机构中的角色背景或其网络系统安全策略,这可能是您唯一可用的解决方案。

Testing

测试

Create a file _foobar.html:

创建一个文件_foobar.html

<!DOCTYPE html>
<html>
  <head></head>
  <body>
    <h1 style="color: green;">Hello</h1>
    <h1 style="color: blue;">World</h1>    
  </body>
</html>


Answering strictly the question asked by Gagan

严格回答加根提出的问题

How is a browser supposed to render css which is non contiguous?

  1. Is it supposed to generate some data structure using all the css styles on a page and use that for rendering?
  2. Or does it render using style information in the order it sees?

浏览器应该如何呈现不连续的 css?

  1. 是否应该使用页面上的所有 css 样式生成一些数据结构并将其用于渲染?
  2. 或者它是否按照它看到的顺序使用样式信息进行渲染?

(quote adapted)

(报价改编)

For a more accurate answer, I suggest Google these articles:

为了更准确的答案,我建议谷歌这些文章:

  • How Browsers Work: Behind the scenes of modern web browsers
  • Render-tree Construction, Layout, and Paint
  • What Does It Mean To “Render” a Webpage?
  • How browser rendering works?—?behind the scenes
  • Rendering - HTML Standard
  • 10 Rendering — HTML5
  • 浏览器的工作原理:现代网络浏览器的幕后
  • 渲染树构建、布局和绘制
  • “渲染”网页是什么意思?
  • 浏览器渲染是如何工作的?—?幕后
  • 渲染 - HTML 标准
  • 10 渲染——HTML5