Reputation: 1
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.
Upvotes: 0
Views: 2091
Reputation: 1185
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>
Upvotes: 0
Reputation: 399
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.
Upvotes: 1
Reputation: 6552
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>
Upvotes: 0