1.2*_*tts 6 css url css-selectors css3
是否有选择器指定仅在匹配特定URL或URL的一部分时应用的CSS?
例如,这是我的CSS样式表:
p {
color: green;
}
url("home.html") {
color: blue;
}
url("about.html") {
color: yellow;
}
path("/path/index*") {
color: indigo;
}
Run Code Online (Sandbox Code Playgroud)
当用户访问home.html时,我希望应用home.html选择器.当我在about.html网址上时,我希望应用about.html.
CSS媒体查询允许您在视图宽度更改时切换到另一组样式.当用户要在屏幕上查看或将其发送到打印机时,它还允许您指定一组不同的样式.
我的问题是,"是否可以根据URL或URL中的值指定不同的样式集." 所以这不是一个如何做我要问的问题,而是如果可能的话.
我正在使用CMS,它有一个主题,允许您添加自己的CSS.有一个样式表.而已.不是两个而是一个.
我有一个页面具有该页面的特定CSS,只有该页面.这是这个问题的起源.可能有一千种解决方法,但我的问题不在于解决方法.
1.2*_*tts 11
看起来这条@document规则只是针对这种情况提出的,但它已从 CSS3 规范中删除并计划用于 CSS4。从我的测试来看,它似乎不受支持,并且在发布时它没有在caniuse上列出。
语法如下:
@document url("http://www.example.com/widgets/") {
body {
color: white;
background: tomato;
}
}
/* The above applies styles only to the page at the given URL */
@document url-prefix("http://www.example.com/widgets/") {
/*
Styles written here are applied to all URLs that
begin with 'http://www.example.com/widgets/'
*/
}
@document regexp("https:.*") {
/* Styles written here are applied to all URLs that begin with 'https:' */
}
Run Code Online (Sandbox Code Playgroud)
使用@media查询进行比较的测试代码:
var styleTag = document.createElement ("style");
document.head.appendChild (styleTag);
var sheet = styleTag.sheet;
sheet.insertRule ("@media (min-width:600px) { html {color:red}}", 0);
console.log(document.styleSheets.length);
Run Code Online (Sandbox Code Playgroud)
结果:
// no errors, stylesheet is added
Run Code Online (Sandbox Code Playgroud)
测试代码测试@document规则:
var styleTag = document.createElement ("style");
document.head.appendChild (styleTag);
var sheet = styleTag.sheet;
sheet.insertRule ("@document url('http://www.google.com') { html {color:red}}", 0);
Run Code Online (Sandbox Code Playgroud)
结果:
/*
Exception: SyntaxError: An invalid or illegal string was specified
@Scratchpad/3:4:0
*/
Run Code Online (Sandbox Code Playgroud)
感谢@BoltClock,TIL 关于@document
更多信息