Load CSS based on URL variable in HTML page
Asked Answered
C

2

9

I'd like to load a stylesheet when my URL variable contains "?view=full".

Is it possible to do this in HTML (i.e. not PHP)? If so, how?

Contaminate answered 26/5, 2011 at 23:32 Comment(2)
Can you use JavaScript as well, or just HTML?Brockbrocken
Are you trying to have different CSS for a normal view and a print view? It may be better to use CSS media types, which allow you to specify different stylesheets for screen, mobile, and print.Propitiatory
P
11

It’s not possible in pure HTML; you'd have to use either PHP or JavaScript. If you want to do it in JavaScript, you could put this in your <head> section:

<script>
if (window.location.search.indexOf('?view=full') === 0)
    document.write('<link rel="stylesheet" href="theStylesheet.css" />');
</script>
Primordial answered 26/5, 2011 at 23:34 Comment(3)
@alex: That actually only applies to the <script> tag, not any other tag.Primordial
How would this be doen with PHP?Evangelist
@Shae: <?php if (isset($_GET['view']) && $_GET['view'] === 'full') { ?><link rel="stylesheet" href="theStylesheet.css" /><?php } ?> or something. isset might not be necessary, it’s been a while since I’ve written PHP.Primordial
W
4

This will create the link element in your head element if that GET param is present.

if (window.location.search.search(/[?&]view=full(?:$|&)/) !== -1) {
    var link = document.createElement('link');
    link.type = 'text/css'; 
    link.rel = 'stylesheet';
    link.href = 'path/to/it.css';
    document.getElementsByTagName('head')[0].appendChild(link);
}
Woodhead answered 26/5, 2011 at 23:37 Comment(3)
That's incorrect - you need a <link> element. <style> elements do not have an href attribute, nor a rel attribute.Primordial
@minitech Whoops, my mistake. I've fixed.Woodhead
Um... "nemesis"? Anyways, yes :)Primordial

© 2022 - 2024 — McMap. All rights reserved.