Reputation: 75
My site style is divided in two parts:
@media only screen and (max-width: 725px) {
/* a lot of styles for small screens */
}
@media only screen and (min-width: 725px) {
/* a lot of styles for big screens */
}
I have a situation in which I would love to force small screen style, despite current screen size being wider. So, basically, I want to force the mobile look on desktop.
Keep in mind that I don't have option to change too much things in css, and styles should remain inside the media queries.
What is best approach to accomplish this? I would prefer a solution using JavaScript.
Upvotes: 4
Views: 3030
Reputation: 1318
I'm not sure it's possible to force the rendering of media query styles for non-matching media. I feel like you've laid out the challenge pretty clearly, though, so I have a suggestion as to how you might solve in a way I know will work.
The way CSS works, any rule you write will apply to all matching elements unless something either more specific or more recent overwrites it.
Since you know you always want mobile styles on mobile, by removing the media query from your mobile styles, you'll set the mobile presentation to be your default look.
Since you know you only sometimes (even if that "sometimes" is really "almost always") want the desktop styles to appear for larger screens, you can set yourself up with a way to toggle them. For me, the easiest way to do this is to add an ID to the body tag and to the beginning of every desktop declaration.
//small screen styles
/* a lot of styles for small screens */
//conditional wide-screen styles
@media only screen and (min-width: 725px) {
#wideLayout //styles
#wideLayout //styles
#wideLayout //styles
}
With your CSS arranged like this, the wide screen styles will only apply when both the screen is wide enough and there's a top-level parent that has the ID #wideLayout
. And (as requested) you can use javascript to toggle those styles simply by toggling that ID.
Example:
$('#toggleLayout').on('click',function(){
if ($('section').attr('id') == "wideLayout"){
$('section').attr('id','');
} else {
$('section').attr('id','wideLayout');
}
});
/*small screen styles*/
div {background-color:#484;display:inline-block;width:50px;height:50px;margin:10px;}
/*conditional wide-screen styles*/
/*I changed the query here so the preview window would be wide-enough to demonstrate*/
@media only screen and (min-width: 125px) {
#wideLayout div {background-color:#848;display:block;width:auto;height:80px;margin:10px 0 0 0;}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button id="toggleLayout">Toggle Layout</button>
<section>
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>
<div>6</div>
<div>7</div>
<div>8</div>
</section>
Here's a jsfiddle that you can use to play with my solution: https://jsfiddle.net/sq8jhu93/2/
Upvotes: 2