I'd like to emphasize where a web application is loaded from: the local development environment vs a test or production environment. To keep things simple, the mechanism should work just on CSS. But so far my CSS is a static file.
Is it possible to write a CSS that evaluates on the browser what background color to use, maybe based on the URL it was loaded from (localhost vs other hosts)?
Somehow I am hoping to get a solution based on CSS Conditional Rules.
I don't think this is possible using CSS, however you can do this using JavaScript. Checking if the current URL that is visited contains a certain string. Then changing style, you can also of course add a class within the if statement.
If you were to run this snippet in the answer it is blue, if you run this snippet on your localhost it will be red.
if (window.location.href.indexOf("stackoverflow") > -1) {
document.body.style.backgroundColor = 'red';
} else {
document.body.style.backgroundColor = 'blue';
}
The following screenshots will show how it effectively changes the background color based on the URL entered in the browser.
Without localhost in the name;

With localhost in the name;

To ignore everything that comes after the hostname and only take a look at the hostname and port you can use location.host seen in the following snippet.
if (window.location.host.indexOf("localhost") > -1) {
document.body.style.backgroundColor = 'red';
} else {
document.body.style.backgroundColor = 'blue';
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With