Shafizadeh
Shafizadeh

Reputation: 10340

How to apply @media for css attribute that are set via jquery

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

Answers (5)

Gho
Gho

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

Blix
Blix

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

Danish Khan
Danish Khan

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

Thibault
Thibault

Reputation: 137

You have to specify a @media type, for example :

@media screen and (max-width 768px) {
//Your declaration here
}

Upvotes: -1

George
George

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

Related Questions