【问题标题】:Media query affecting non existent class影响不存在的类的媒体查询
【发布时间】:2019-09-20 20:14:13
【问题描述】:

短版,为什么我看到的是绿色和蓝色,H2s 而不是红色和蓝色?

加长版 如果您只看代码,这可能会更容易,但无论如何我都会解释一下。 我有一个默认的 H1、H2、H3 文本颜色,蓝色。我有一个媒体查询,它检测到浏览器大小超过 768 像素(网站的桌面版)。

在媒体查询中,我将 H1、H2、H3 的颜色设置为红色。有一个名为“bar”的类也有 h1,h2,h3 颜色样式,这次是绿色。

有一个“foo”类的 div。没有带有“bar”类的 div。

如果我在媒体查询中添加一个“foo”类(黄色),它会按预期工作,如果我再次删除 bar 类,一切都很好。但是如何将 H2 分配给一个影响没有与之关联的类名的 div 的类?尤其是在媒体查询中设置了默认 h2 时。我希望看到红色和蓝色,而不是绿色和蓝色。

谁能向我解释为什么我会看到这种行为?

<!doctype html>
<html lang="en">
<head>
     <meta http-equiv="content-type" content="text/html; charset=UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>hi</title>
    <meta name="description" content="this">
<style>
 h1,h2,h3{
     color:blue;
 }
 /*Desktop layout*/
@media (min-width: 768px) {
     h1,h2,h3{
         color:red;
     }

    .bar h1,h2,h3{
        color:green;
    }

}
</style>
</head>
<body>
<div class="foo">
    <h2>me foo</h2>
    <p>you bar  </p>
</div>
</body>
</html>

【问题讨论】:

    标签: css


    【解决方案1】:

    您的问题在于您的.bar 选择器:

    .bar h1,h2,h3{
       color:green;
    }
    

    使用此选择器,您可以将所有&lt;h1&gt; 标记定位到具有.bar 类的元素内,以及HTML 文档中的所有&lt;h2&gt;&lt;h3&gt; 标记。

    您应该改为:

    .bar h1, 
    .bar h2, 
    .bar h3 {
       color:green;
    }
    

    这将只针对 .bar 类中的孩子。

    了解更多关于组合器和选择器列表here

    【讨论】:

    • 哦,好酷。好吧,多年来我一直在做错事。 :/ 感谢您的快速回复!
    【解决方案2】:

    您目前只覆盖 h1 而不是 h2、h3。 将您的代码更改为:

    <!doctype html>
    <html lang="en">
    <head>
         <meta http-equiv="content-type" content="text/html; charset=UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>hi</title>
        <meta name="description" content="this">
    <style>
     h1,h2,h3{
         color:blue;
     }
     /*Desktop layout*/
    @media (min-width: 768px) {
         h1,h2,h3{
             color:red;
         }
    
        .bar h1,.bar h2, .bar h3{
            color:green;
        }
    
    }
    </style>
    </head>
    <body>
    <div class="foo">
        <h2>me foo</h2>
        <p>you bar  </p>
    </div>
    </body>
    </html>
    

    【讨论】:

      猜你喜欢
      • 2023-03-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多