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?
2 Answers
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'));
6 Comments
sid
you can additonal differences of CSS in additonal files, that will work
DJS
I wan't to do it with Javascript and without loading in additional files. Is that possible?
DJS
Thanks, but it is not so handy because the differents in the styling will be minimal, so it is really necasarry not to make two different stylesheets for small differentses
Noam
CSS itself is not aware of the URL of the page, so it is not possible with only CSS - you need some script either on server side or client side. I suggest referring to different classes of some high-level element and set the proper class with JavaScript.
DJS
@Noam Thanks, how can you check the url for that?
|
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 class="variant-text">A text with two possible backgrounds</div>
5 Comments
DJS
Thanks! But what does that first part in the
if-statement mean? (/\.be$/)Noam
It's a regular expression matching a string that ends with ".be". It's not the only way to analyze the string but it's a useful one.
sid
Convienent if its just one class to add. Likely to get dirty if I have multiple elements to add classes.
Noam
@sid you can make as many changes as you wish depend on a single class. You only need additional classes if you have additional conditions.
DJS
@Noam Thanks for the help. I have combined Sid's solution with yours and now m problem is solved!
class="domain-nl"orclass="domain-be"on the body. Or if you hate your users, use JavaScript to check the URL domain and dynamically load a style sheet ;)