Search code examples
htmlcssmedia-queries

HTML viewports vs media query


So far, my rule of thumb is to use viewport units for simple webpages, because it gives the website a lot of flexibility; but when the webpage is complex, use media queries.

There are some intermediate cases where I use both, just because it is easier. The next link is an example I built: https://codepen.io/santimirandarp/pen/jjboKN the css file looks like this:

body{
  background-color:lightblue;
  text-align:center;}
main{

font-size:calc(10px + 0.5vw);
 margin: auto;
width: 80vw;
}
#title{
  color:magenta;
}
span{
color:hsl(110,100%,55%);
font-size:calc(20px + 3vw) ;
}
#description{}
p{font-size:calc(13px + 0.5vw) ;
text-align:justify;
line-height:calc(20px + 0.5vw);
margin-bottom:2vw;
}

#linend{
  color:blue;
  text-align:center;
  font-family:Garamond;
  font-size:1.5em;
  background-color:yellow;
}

@media only screen and (min-width: 1000px) { @media only screen and (min-width: 1000px) { 
  main{width:45%;}

  p {font-size:100%;
  }
  p strong{font-size:100%;
  color:brown;}

  }

Question

Is this approach correct? When to use viewport units vs media queries? Can you explain the right approach?


Solution

  • As of MDN:

    Media queries are useful when you want to modify your site or app depending on a device's general type (such as print vs. screen)

    In comparison, the purpose of the viewport is to adapt on the screens dimensions, like width and height.

    That in mind, there is no 'use viewport or media queries'. With media queries you can differentiate media types - not only their dimensions. For example, when you have media print, you might want to remove colors. Additionally (not alternatively) you can use viewport units to specify the dimensions.

    Since you are using both media queries and viewport units, my answer would be: yes, your approach is right. Though, I don't think there is a strict right or wrong here.