Gaspa79
Gaspa79

Reputation: 5615

Media queries inside CSS classes

So I'm trying to do something like this:

.myClass
{
    @media all (max-width: 1024px) {
        left: 33%;
    }
    @media all (min-width:1025px) {
        left: 25%;
    } 
}

but for some reason isn't working. Is there any way I could achieve this?

EDIT: I know that you can achieve that by putting the media queries outside, but I don't want to do that =(

Upvotes: 5

Views: 11130

Answers (6)

Francesco
Francesco

Reputation: 111

This is an old thread but, apparently in 2024 you can nest media query inside CSS classes without using SASS.

Here you can find an example: https://css-tip.com/better-modern-css/

Anyway, I'm still figuring which browsers support it.

Cheers

Upvotes: 3

Ashutosh Biswas
Ashutosh Biswas

Reputation: 117

The problem's core lies in the syntax of CSS statements. There are two kinds of statement in CSS:

  • CSS rules(i.e. rulesets)
  • At-rules

@media is a type of at-rule. CSS rules can be nested inside @media. But inside a CSS rule $media or any other at-rule can't be nested in a syntactically valid way and thus if it's done so, it is ignored.

References:

Upvotes: 3

Otim Fredrick
Otim Fredrick

Reputation: 361

The problem is that you're trying to set the media queries inside a class.

You have to set them outside any class and inside the querys you could override your classes you want to change on different views.

To learn more About media-queries take a look at its documentation

.myClass
{
   // default style
}

@media all (max-width: 1024px)
{
    .myClass {
        left: 33%;
    }
}

@media all (min-width:1025px) {
    .myClass {
        left: 25%;
    } 
}

Upvotes: 6

Pranab Mitra
Pranab Mitra

Reputation: 389

Can you please try with the followings:

   @media (max-width: 1024px) {
      .myClass {
        left: 33%;
      }
    }

    @media (min-width: 1025px) {
      .myClass {
        left: 25%;
      }
    }

Upvotes: 0

Allan Pereira
Allan Pereira

Reputation: 2570

This syntax is not valid in CSS. You should use:

@media all (max-width: 1024px) {
    .myClass{
        left: 33%;
    }
}
@media all (min-width:1025px) {
    .myClass{
        left: 25%;
    }
} 

Upvotes: 0

ScaisEdge
ScaisEdge

Reputation: 133400

In think you shoudl use

 @media all (max-width: 1024px) {
     .myClass  {
        left: 33%;
      }
 }

@media all (min-width:1025px) {
     .myClass  {
        left: 25%;
      }
}

Upvotes: 0

Related Questions