<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>

一个浏览器应该如何渲染css是不连续的?它是否应该生成一些数据结构,使用页面上所有的css样式,并使用它进行渲染?

还是按照看到的顺序使用样式信息进行渲染?


当前回答

当我看到大型站点的内容管理系统经常将一些<style>元素(一些,而不是全部)放置在依赖于这些类的内容附近时,我就得出结论说,情况已经不一样了。

去看看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>在<body>中经过深思熟虑的使用已经越来越成为主流。

其他回答

不是有效的HTML,反正几乎每个浏览器都只考虑第二个实例。

在Fedora下测试FF和谷歌Chrome的最新版本,在XP下测试FF、Opera、IE和Chrome。

我认为,在现代浏览器中,你只需付出一点努力,就可以获得完全合法的“作用域样式”。考虑下面的HTML文档:

<!doctype html>
<html>
    <head>
    </head>
    <style>p{background:red}</style>
    <body>
        <template>
            <style>p{background:green}</style>
            <p>I am green</p>
        </template>
        <p>I am red!</p>
        <script>
         document.querySelectorAll('template').forEach((template)=>{
             const div = document.createElement('div');
             div.remove(); // detach div from document
             let shadow = div.attachShadow({mode:'open'});
             shadow.replaceChildren(template.content);
             template.replaceWith(div);
         });
        </script>
    </body>
</html>

我使用了一个模板来封装HTML,我想包含自己的样式元素,不影响模板之外的任何HTML。当然,默认情况下,在呈现期间忽略模板。JavaScript代码

查找文档中的每个模板 创建一个分离的空div 赋予div一个“阴影根”(本地化样式的关键) 将模板内容复制到影子根目录 用包含相同内容的div替换原来的模板(除了在阴影根)

几乎所有HTML内容(包括样式)在模板中都是合法的。

使用最新的Chrome/Firefox/Edge测试。给我一个免费的MacBook Pro,我会用Safari进行测试!: -)

是的,它可以。我查看了Mozilla的网页。 https://developer.mozilla.org/en-US/docs/Web/HTML/Element/style

在您的示例中,浏览器“不应该”做任何事情。HTML无效。要么触发错误恢复,要么解析器自行处理。

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

我想这将因浏览器的不同而有所不同:全局显示规则可能会随着浏览器运行代码而更新。

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

无论如何,它都不是有效的HTML,所以我认为考虑它是徒劳的。<style>标签属于页面的头部部分。