CSS: Is it possible to create a class which only overrides properties within a given media query?

92 Views Asked by At

This is my class:

.center-block-xs {
  // This style is given to an image. I want the image to keep
  // its original CSS (whatever the default display and margin
  // is for an image) unless the screen size fits within the 
  // media query below.
}

@media(max-width:767px) {
  .center-block-xs { 
    display: block; 
    margin-right: auto; 
    margin-left: auto; 
  }
}

Basically, what I want to do is this: If an element has the class .center-block-xs, then the CSS should be applied to the element only if the screen size is within the media query. I know I can do this:

@media(max-width:767px) {
  .color-red-xs { color: red; }
}

@media(min-width:768px){
  .color-red-xs { color: black; }
}

In which case the color is red only if the screen size is within the media query, otherwise it gets overridden with the black color. But I don't want to have to override any CSS in my case; I just want the CSS to be what it normally would be unless the screen size is within the media query. Is this possible?

2

There are 2 best solutions below

0
On BEST ANSWER

What you're describing is precisely how CSS and media queries work by default. If you define a class of .center-block-xs within a media query, that definition will only be applied to elements that a) have that class, when b) the media-query rules apply. There is no need to explicitly define the alternative case(s) if you want inherited styles to be applied.

0
On

Just set the default color to what you want, such as the following:

.center-block-xs {
   color: red;
}

Then set a minimum width for the CSS change, like so:

@media(min-width: 767px) {
  .center-block-xs {
    color: black;
  }
}

when the screen hits a width of 767px, the text will change.