Different background color depending on URL

Issue

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.

Solution

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.host.indexOf("stackoverflow") > -1) {
  document.body.style.backgroundColor = 'red';
} else {
  document.body.style.backgroundColor = 'blue';
}

The following screenshots will show how it affectively changes the background color based on the URL entered in the browser.

Without localhost in the name;
enter image description here

With localhost in the name;
enter image description here

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';
}

Answered By – FUZIION

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published