Reputation: 10340
My website is responsive, I've set a CSS attribute via jQuery, But there is a problem, when I use of @media
(for mobile display), that attribute does not change, why ?
HTML code:
<div class="test">foo</div>
JQuery code:
$(".test").css({'margin' : '20px'});
CSS code:
@media (max-width: 599px){
.test {margin: 10px;}
}
Why @media
does not works? And how it works ?
It should be noted that the output is always margin : 20px
(for all @media
size)
Upvotes: 1
Views: 904
Reputation: 568
Jquery applies it's css on the element, which has a higher importance than your class in css...if you really need to, you can add .test {margin: 10px !important;}
in that media query of yours. hope this helps
Upvotes: 0
Reputation: 289
Because you are trying to overwrite javascript CSS (applied with jQuery) with css CSS. CSS applied by javascript has always priority.
Upvotes: 0
Reputation: 143
.test {border:1px solid #000}
@media (max-width: 1024px){
.test {margin: 20px;}
}
@media (max-width: 599px){
.test {margin: 10px;}
}
<div class="test">foo</div>
Upvotes: 0
Reputation: 137
You have to specify a @media type, for example :
@media screen and (max-width 768px) {
//Your declaration here
}
Upvotes: -1
Reputation: 36784
Because JavaScript, and by further extension jQuery, adds CSS styles inline, so they take precedence over any styles that are applied in your stylesheet.
Use another class rather than using .css()
:
.margin{
margin: 20px;
}
@media (max-width: 599px){
.test {margin: 10px;}
}
And then add the class using jQuery and .addClass()
:
$(".test").addClass('margin');
Upvotes: 4