简体   繁体   中英

Change element.style with media query

Is there a way that I can change the element.style with a media query? I have these boxes on my webpage that are created in html using:

<div class="colored-box" style="width:400px;height:193px;border:5px solid #8CDADF;"></div>

At different screen size, I need that width to get larger to fit correctly, is there anyway to change that in CSS within a media query.

You can't change style attribute with media querie. You need to use JavaScript for it. What you could do is to change the current class:

<div class="colored-box">aaa</div>

<style>
.colored-box {
  width:400px;
  height:193px;
  border:5px solid red;
}

@media (max-width: 300px) {
  .colored-box {
    width:400px;
    height:193px;
    border:5px solid green;
  }
}
</style>

If you have control over the HTML (I am not sure from your question if you do or not) you can use CSS variables in the style attribute and then redefine them with media queries.

Such as:

 .colored-box { --box-width:400px; } @media screen and (min-width: 1000px) { .colored-box { --box-width:800px; } } 
  <div class="colored-box" style="width:var(--box-width);height:193px;border:5px solid #8CDADF;"></div> 

Yes, you can easily do that. I would recommend not using in-line styling since you can't overrule in-line styling with a media query that adjusts the class (not to mention in-line styling is usually bad practice). Here's how you would do that:

<style> 
  .colored-box {
  width: 400px;
  height: 193px;
  border: 5px solid #8CDADF;
}

@media screen and (min-width: 1500px) {
  width: 800px;
}
</style>


<html>
  <div class="colored-box"></div>
</html>

Alternatively if you just want a quick-fix and to keep the code you have you can use !important like this:

@media screen and (min-width: 1500px) {
  width: 800px!important;
}

But this is considered bad practice and I wouldn't recommend it.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM