css媒体怎么去除背景图效果


<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <meta http-equiv="x-ua-compatible" content="ie=edge">
        <title></title>
    </head>
    <body>
        <style type="text/css">
        
        @media (max-width: 768px) {
            #test{
                /* 没有效果 */
                background-image: none;
            }
        }
        
            #test {
                background-image: url(无标题.png);
                background-repeat: no-repeat;
                width: 100%;
                height: 500px;
            }
        </style>
        <div id="test">
            <div style="width: 100px;height: 700px; background-color: red;">
                
            </div>
        </div>
        123
    </body>
</html>

image.png

需要在768px以下的屏幕去除背景图效果, 如何实现?
以下原先则效果
image.png

以下是需要实现的效果

image.png

阅读 3.2k
4 个回答

其实是已经生效了的,只是因为 CSS 优先级的原因,你原先的顺序导致 media 的样式被覆盖了,你可以把媒体查询的样式放在后面去。

<style type="text/css">
    #test {
        background-image: url(无标题.png);
        background-repeat: no-repeat;
        width: 100%;
        height: 500px;
    }

    @media (max-width: 768px) {
        #test {
            /* 没有效果 */
            background-image: none;
        }
    }
</style>

@media (max-width: 768px) {
  #test{
    background-image: none !important;
  }
}
        

<!DOCTYPE html>
<html>

<head>

<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<title></title>

</head>

<body>

<style>
    #test {
        background-image: url(./image/成功.png);
        background-repeat: no-repeat;
        width: 100%;
        height: 500px;
    }
</style>
<div id="test" style="background-image: none;">
    <div style="width: 100px;height: 700px; background-color: red;">

    </div>
</div>
123

</body>
</html>

html代码


<div class="parent">
    <div class="child"></div>
</div>

<h1 class="text">Hello</h1>

css代码


<style type="text/css">
    /* 
    @media (max-width: 768px) {
        .parent {
            不会生效, 除非 !important
            background-image: none !important;
        }
    }
     */

    .parent {
        height: 500px;
        background-image: url(test-bg.png);
        background-repeat: no-repeat;
    }

    .child {
        width: 100px;
        /* 子元素高度超出了父元素 */
        height: 900px;
        background-color: red;
    }

    /* 媒体查询写在后面, 可以覆盖前面定义的样式 */
    @media (max-width: 768px) {
        .parent {
            background-image: none;
        }
    }
</style>

大屏幕
image.png

小屏幕
image.png

背景确实删了, 高度还在, 需要这样写
由内容撑开高度即可


.parent{
    height: auto;
}

image.png

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题