CSS:是否可以创建一个 class 只覆盖给定媒体查询中的属性?

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

这是我的 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; 
  }
}

基本上,我想做的是:如果一个元素有 class .center-block-xs,那么只有当屏幕尺寸为在媒体查询中。我知道我可以做到:

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

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

在这种情况下,仅当屏幕尺寸在媒体查询范围内时颜色为红色,否则它会被黑色覆盖。但我不想在我的情况下覆盖任何 CSS ;我只希望 CSS 成为它通常的样子,除非屏幕尺寸在媒体查询范围内。这可能吗?

您所描述的正是 CSS 和媒体查询在默认情况下的工作方式。如果您在媒体查询中定义 .center-block-xs 的 class,则该定义将仅应用于 a) 具有 class 的元素,当 b) 媒体查询规则适用时。如果您希望应用继承的样式,则无需明确定义替代案例。

只需将默认颜色设置为您想要的颜色即可,例如:

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

然后为 CSS 更改设置最小宽度,如下所示:

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

当屏幕达到 767px 的宽度时,文本会发生变化。