celsomtrindade
celsomtrindade

Reputation: 4671

@media not working properly

I'm building a website using bootstrap, but when i want to make some changes in the CSS for mobile devices, my @media doesn't work in the way i was expecting.

HTML

<div class="container">
    <div class="main">
        <div class="col-lg-12">
            <hr class="style" />
            <h2>Main Title</h2>
        </div>
    </div>
</div>

CSS

h2 {font-size: 30px;}
.main {background: #000 url(..img/bg.png);}

@media (max-width: 768px) {
    h2 {font-size: 20px;}
    .main {background: #fff;}
}

@media (max-width: 992px) {
    h2 {font-size: 24px;}
}

@media (max-width: 1200px) {
    /* no changes yet */
}

@media (min-width: 1200px) {
  /* no changes yet */
}

As you can see, i'm trying to remove the background img of the main div only in small screen, but it just get ignored and the img is still there. The same goes to the h2, the size is always the same (30px). I was able to change it, but i have to place the propertie inside of each '@media', which will make my css code bigger.

Is there a way to fix this? Ps.: I already google it, was searching here but didn't find anything similar.

Upvotes: 2

Views: 1150

Answers (1)

agconti
agconti

Reputation: 18093

A couple things:

You need to add a meta tag to keep the viewport from virtually scaling on mobile devices

<meta name="viewport" content="width=device-width, initial-scale=1">

You should also define what media the @media query is targeting:

h2 {font-size: 30px;}
.main {background: #000 url(http://placekitten.com/400/400);}

@media screen and (max-width: 768px) {
    .main h2 {font-size: 20px;}
    .main {background: #fff;}
}

@media screen and (max-width: 992px) {
    .main h2 {font-size: 24px; color: blue;}
}

@media screen only and (max-width: 1200px) {
    /* no changes yet */
}

@media screen only and (min-width: 1200px) {
  /* no changes yet */
}

Working demo: http://jsbin.com/pimujahosete/1/edit

Upvotes: 2

Related Questions