-1

I don't understand why media query don't work after I change the width of an HTML element with javascript . If for example an element has INITIALLY a width equal to 200px and then I change its width to 100px programmatically with javascript .So when I expect another change of this width due to media query , it does not work , in fact it keeps the last size made by javascript as illustrated below . So can you explain to me why and can tackle this issue ?

// Embedded CSS : initial width 
 #main { width:48%} 

let main = document.getElementById("main"); // html element
main.style.width="48%";

// css media query code which does not work due to javascript change
@media(max-width: 550px) {
  #main { width:100%}
}

NB: IF NO CHANGE IS MADE BY JAVASCRIPT EVERYTHING IS OK

2
  • First you have to add your code in question to get more help .... but in general JavaScript will add inline styling which is stronger than external styling made by the media query try to use !important inside your media query code Commented Apr 2, 2021 at 4:10
  • @IbramReda ok added some illustration for you .Thanks in advance Commented Apr 2, 2021 at 4:26

2 Answers 2

1

You could try !import in your media query ... the width will be 100% even if you try to change it by JavaScript it will be 100% for screen less than 550px

full working example

const btn = document.getElementById("btn");
const main = document.getElementById("main"); 
btn.addEventListener("click",function(){
  main.style.width="60%";
})
#main{
  height:20px;
  width:48%;
  background-color:#00f;
  margin:auto;
}


@media(max-width: 550px) {
  #main { width:100% !important}
}
<div id="main"></div>
<button id="btn">set style to 60% by js</button>

Sign up to request clarification or add additional context in comments.

Comments

0

What javascript syntax did you use? If you use this syntax for example

document.getElementById("elem").style.width = "500px";

then it'll returns to an element's attribute not its css style

<div id="elem" style="width: 500px">Hello World!</div>

Fyi, media query only works if there're no any style added on inline-style, except if you add !important query on your css.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.