Using media queries in a <style> tag

How to put “@media screen and” command in a <style> tag with modern CSS (after year 2020)?

I have this code:

@media screen and (max-width: 320px) {
    .example {
        display: block;
     }
}

I want to put it in a <style> tag, but throughout the years I read time and again that it’s not possible to put @media screen and codes inside style tags (at least with the standard syntax).

Now in year 2022, is there any “good” way to do so? Thanks,

Do you have a sample piece of code to show what you’re trying to do that fails? I have to say I use media queries all the time with “screen” and they work fine. I use them in external style sheets, but to my knowledge they will work fine inside a section too.

2 Likes

Have you tried adding a media query inside your style tag to see if it works?

/* I always use @media only - also I have noticed 675px is a great overall mobile breakpoint.*/
@media only screen and (max-width:675px) {
    .example {
        display: block;
     }
}

Media queries work fine inside style tags and always have.

They don’t work in style attributes as only property/values are allowed in style attributes.

You should avoid using the style attribute anyway unless you have a special case reason.

There I did it for you :slight_smile:

<style>
@media screen and (max-width: 320px) {
    .example {
        display: block;
     }
}

</style>

I think you must mean something else :wink:

No, I confused style attributes with style tags.

I meant “how to use”, not “how to put”, sorry for the embarrassing mistake.

Indeed, I confused style tags with style attributes after not seriously working with CSS several years.

No, I knew it works, I confused style attributes with style tags.

I can’t edit the question, sadly.

It’s ok I think people will get the gist of the conversation :slight_smile:

Yes using media queries in style attributes will not work because that’s not what they were designed for and doesn’t really make any sense. I can’t really think of a ‘use-case’ for this anyway so perhaps if you explain what and why you think you need them then we may be able to offer an alternative answer. :slight_smile:

1 Like

Was literally asking if he had tried adding it yet before posting the question.

1 Like

Yes I wasn’t really replying to your post but the OPs original question. I must have quoted the wrong person :wink:

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.