<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文档:
<!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进行测试!: -)