I'm having some issues trying to add media queries with jQuery/javascript. I have a <div class="container">
hidden on small screens with display: none
. I want to use the code below to make it show up, although I don't get any errors nothing changes.
$('.container').append('<style type="text/css">@media screen and (min-width: 1012px){ .container { "display": "block"}}</style>');
Any suggestions? Thank you.
It's will work fine if you only delete double quotes form "display": "block"
$('.container').append('<style type="text/css">@media screen and (max-width: 1012px){ .container { display: block}}</style>');
but I think better if you change your selector
$('head').append('<style type="text/css">@media screen and (max-width: 1012px){ .container { display: block}}</style>');
You can use
document.querySelector('style').textContent +=
"@media screen and (min-width: 1012px){ .container { display: 'block'}}"
Get style element and add your new rules, and your html add if no exists
<style>......</style>
The answer of CMedina is quite good, but it appends to the first style element in the document. This could be problematic in two ways:
a) There might not be style element (because <link rel="stylesheet">
);
b) There might be more than one style element. Appending style rules to the first one might be overwritten by later ones.
So here's my tactic: create a new <style>
element; fill with desired content; append to the body so it comes last
const styleSheet = document.createElement('style');
styleSheet.textContent = '@media print { /* ... */ }';
document.body.appendChild(styleSheet, 'beforeend');
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.