Hide background image using Media Queries

2019-07-17 04:56发布

问题:

I'm attempting to remove my background image when people view the site on mobile devices.

Here's my code.

HTML:

<section id="Build">
    <div class="img_contain col-xs-8">
        <img src="assets/images/RockS_BG.png" ">
    </div>
    <div class="column-right col-xs-4 ">        
        <h1>Build</h1>      
        <p>
            BLA BLA BLA         
        </p>
    </div>
</section>

CSS:

#build {
    background-image: url('../images/buildbg.png');
    margin: 0 auto;
    text-align: left;
    padding-top: 40px;
    background-color: #D89330;
}

Is it possible to hide a background image using media queries? I understand that I could hide elements like the Divs, paragraphs etc etc, but I haven't seen any info on hiding a background image with media queries.

回答1:

You can use media query to disable bacground in low resolution screens.

Try this with values as needed:

@media only screen and (max-width: 599px) and (min-width: 600px)
    #Build {
        background-image:none;
    }
}

You will have to adjust the attributes depending on the device!

Also take a look at this blog post by Tim Kadlec that walks through the various scenarios for conditionally displaying a background image.



回答2:

An expansion on Tamil Selvan's answer, using the syntax @media <criteria> can make it so your css will only apply to what you want it to.

JSFiddle DEMO.

You'll see the image disappear at the 600px mark when resizing.

CSS:

#build {
    text-align: left;
    padding: 30px;
    background: url('http://i.imgur.com/DFlOcoF.jpg') center no-repeat, #D89330;
}

@media screen and (max-width: 600px) {
    #build {
        background: #D89330;
    }
}

You can read more on CSS Media Queries at the Mozilla Developer Website and CSS Tricks.

Note that there is no specific way to detect whether the browser is a mobile phone. You can however check the screen size, pixel density ratio or browser type.



回答3:

@media screen and (max-width: 600px) {
    #Element_which_to_hide_bgimage{
        background: #D89330;
    }
}

It assign bgcolor instead of the bgImage