Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Force media query to be applied

I have this html and css code:

<div class="wrapper">
    <div class="a"></div>
    <div class="b"></div>
</div>

@media all and (max-width: 400px), (max-height: 300px) {
    .wrapper .a {
        ....
        ....
    }
    wrapper. .b {
        ....
        ....
    }
    ....
    ....
}

Now I want that whenever wrapper gets the class "like-small", all the styles of small screen will apply even if the screen is not small. I don't want to duplicate the css code inside the media query. How can I solve that?

Another solution is to force media query to apply. Is there any way to do it?

like image 711
Naor Avatar asked Mar 27 '13 09:03

Naor


People also ask

How do you fix media query not working?

This may be the reason why your media queries aren't working. That is to say, you may have declared CSS within your HTML document. So if this is the case, simply go through the HTML document and remove the CSS declared inline.


2 Answers

You can try with javascript. This sentence sets the viewport width and forces browser to apply your media query:

$('meta[name="viewport"]').prop('content', 'width=400');

This is taken from this answer: https://stackoverflow.com/a/20137580/1401341 As someone says in the comments, this will work only with browsers which support viewport tag.

like image 96
Fernando Avatar answered Oct 16 '22 17:10

Fernando


You can do something like this with a bit of javascript.

In a nutshell, you'll move your media queries out of the css, and test them in JS using window.matchMedia.

When you know which one matched, you can add a className to the <html> tag, similar to the way Modernizr works. So on a phone you'd see <html class="like-small">.

Your css will be written to take advantage of those convenience classes, rather than using the native media query:

.like-small wrapper.a {}
.like-large wrapper.a {}

(I also like to add .not-like-small, .not-like-medium classes to <html> as well, to further simplify the css)

So now, after the regular media query is matched and the appropriate classname is appended to the document, RWD works pretty much as normal. And if you want to force a particular style you can just rewrite the classNames on the HTML tag to affect the entire page, or add a className to any parent element to affect only part of the page.

like image 30
wwwmarty Avatar answered Oct 16 '22 16:10

wwwmarty