为什么媒体查询的优先级比没有媒体查询的优先级高 [英] Why media queries has less priority than no media queries css

查看:295
本文介绍了为什么媒体查询的优先级比没有媒体查询的优先级高的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道为什么媒体查询的优先级低于普通CSS? 如何解决使媒体查询变得更加重要?

I want to know why the media queries has less priority than normal css? How to work around to make the media queries more important?

@media screen and (min-width: 100px) and (max-width: 1499px) {
  .logo img {
     width: 120%;
  }

}
.logo img{
    width: 100%;
}

<div class="logo">
  <a href="/#!/"><img src="http://www.menucool.com/slider/jsImgSlider/images/image-slider-2.jpg" alt="image"></a>
</div>

推荐答案

这与CSS中Cascade的工作方式有关.当两个冲突的规则针对同一元素时,浏览器使用级联规则确定要应用哪个规则.

This has to do with the way the Cascade in CSS works. When two conflicting rules target the same element, the browser uses the rules of the cascade to determine which one to apply.

选择器特异性是其中最重要的部分:选择器更具体的样式将覆盖选择器更具体的样式...但是 媒体查询不会更改选择器的特异性.这意味着您的两个选择器具有相同的特异性.发生这种情况时,样式表中较晚出现的一个将覆盖较早的样式.

Selector specificity is the most important part of this: styles with a more specific selector will override those with a less-specific selector... but media queries do not change the specificity of your selectors. This means that your two selectors have the same specificity. When that happens, the one appearing later in your stylesheet will override the earlier one.

最简单,最好的解决方法是交换规则集的顺序:

Your easiest and best fix is to swap the order of your rulesets:

.logo img{
    width: 100%;
}

@media screen and (min-width: 100px) and (max-width: 1499px) {
  .logo img {
     width: 120%;
  }
}

通过这种方式,媒体查询会在以后出现,并且在媒体查询与视口大小匹配时会覆盖之前的规则.

This way, the media query comes later, and will override the earlier rule when the media query matches the viewport size.

如果由于某些原因而不是这样,您将需要提高要赢得的规则的选择器特异性.将其更改为以下内容将起作用:

If that's not an option for some reason, you will need to increase the selector specificity of the rule you want to win. Changing it to the following would work:

@media screen and (min-width: 100px) and (max-width: 1499px) {
  .logo img {
     width: 120%;
  }

}
.logo a img{
    width: 100%;
}

这样,选择器现在具有两个标签和一个类或[0,1,2],使其比一个标签和一个类或[0,1,1](每个标签中的零)更具体表示没有特定的ID.

This way the selector now has two tags and a class, or [0,1,2], making it more specific than one tag and one class, or [0,1,1] (the zero in each of those indicates no ids, which are highly specific).

不要不要使用!important来解决此类特异性问题.如果需要在其他位置再次覆盖样式,则唯一的方法是添加另一个!important.最终将导致整个地方出现!important,然后您仍然需要处理选择器的特殊性.

Do not use !important to fix specificity issues like this. If you need to override the style again elsewhere, the only way to do it is to add another !important. This will eventually lead to !importants all over the place, and then you will still need to deal with the specificity of the selectors.

这篇关于为什么媒体查询的优先级比没有媒体查询的优先级高的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆