Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS media query for exact viewport width

Using javascript I create a meta viewport and assign to it a value of 980px. The script is this:

var viewPortTag=document.createElement('meta');
viewPortTag.id="viewport";
viewPortTag.name = "viewport";
viewPortTag.content = "width=980, user-scalable=1";
document.getElementsByTagName('head')[0].appendChild(viewPortTag);

In CSS, is it possible to write a media query that fires only when the viewport width is EXACTLY 980px?

like image 812
Malasorte Avatar asked Jan 30 '15 08:01

Malasorte


2 Answers

Yes, in CSS it is possible to use @media rules to target an exact width.

CSS Example

@media (width: 980px) {
  /* Your CSS */
}

This is telling the browser, when the viewport width is exactly 980px wide, apply the following CSS. When your viewport width changes to 981px or 979px or anything that isn't 980px wide, the CSS will be removed.

Unlike the other answers, this is not using max-width or min-width because the @media rules allow you to just define width, which will target the exact measurement you give it. The width is defined using the viewport width.

Note: You can learn more about the CSS3 @media rule from W3 Schools. Specifically if you look under Media Features, you'll see the available variables, including width all the way at the bottom.

like image 73
Matthew Beckman Avatar answered Sep 28 '22 04:09

Matthew Beckman


You could do something like this. The media query will be triggered at 980px width and would work for width no greater than 980px.

 @media screen and (min-width: 980px) and (max-width: 980px) {
     html {background-color: red !important;}
 }

 html {background-color: green; min-height: 300px;}
like image 32
Alok Swain Avatar answered Sep 28 '22 05:09

Alok Swain