Home > Enterprise >  Different CSS based on URL
Different CSS based on URL

Time:06-02

I have to domains with the same name, one ending with .nl and one with .be. For example domain.nl and domain.be. They follow both the same general styling, but I wan't some elements have a different styling based on if it is .nl and .be. How can I achieve this without loading in additional css files?

CodePudding user response:

If you're using plain Javascript, I'd suggest creating different CSS files for domains; adding just the differences in 2 different files, one for be and one for nl.

somefilename_be.css

{
    body: 'green';
}

somefilename_nl.css

{
    body: 'red';
}

All same styling should go in a common file like common.css.

Then you can load CSS file conditionally based on the domain.

if (window.location.host.split('.')[1] === "be")
    document.write('<link rel="stylesheet" href="somefilename_be.css" />');
else 
    document.write('<link rel="stylesheet" href="somefilename_nl.css" />');

Using JS Frameworks (React, Angular, Vue, Next, Svelte)

if (window.location.host.split('.')[1] === "be")
    import('somefilename_be.css'));    
else 
    import('somefilename_nl.css'));    

CodePudding user response:

If the differences are small, you can rely on a class on the root element, controlled with JavaScript. For example:

if (/\.be$/.test(window.location.host)) {
  document.documentElement.classList.add('variant-be');
}
.variant-text {
  background: yellow;
}

.variant-be .variant-text {
  background: lime;
}
<div >A text with two possible backgrounds</div>

  • Related