Is there a selector that specifies CSS to only applied when matching a specific URL or part of URL?
For example, here is my CSS stylesheet:
p {
color: green;
}
url("home.html") {
color: blue;
}
url("about.html") {
color: yellow;
}
path("/path/index*") {
color: indigo;
}
When the user visits home.html I want the home.html selector to be applied. When I'm on the about.html URL I want the about.html to be applied.
CSS media queries allow you to switch to a different set of styles when the width of the view changes. It also lets you specify a different set of styles when the user is going to view on the screen or send it to a printer.
My question again is, "Is it possible to specify a different set of styles depending on the URL or values in the URL." So it's not a question of how to do what I'm asking but if it's possible to.
I am using a CMS and it has a theme that allows you to add your own CSS. There is one stylesheet. That's it. Not two but one.
And I have one page that has specific CSS to that page and only that page. That is the origin of this question. There may be a thousand workarounds but my question is not about the workarounds.
However since this has been answered I do not mind workaround answers related to the question.
It looks like the @document
rule was proposed for just this case but it was removed from CSS3 spec and planned for CSS4. From my tests it does not appear to be supported and it's not listed on caniuse at the time of this posting.
The syntax is as follows:
@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:' */
}
Test code using @media
query for comparison:
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);
Results:
// no errors, stylesheet is added
Test code testing @document
rule:
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);
Results:
/*
Exception: SyntaxError: An invalid or illegal string was specified
@Scratchpad/3:4:0
*/
TIL about @document thanks to @BoltClock
More info