How can I detect which window dimension is bigger just using CSS media query?

一世执手 提交于 2019-12-12 15:06:07

问题


Does anybody know how to create a media query that would behave like this:

@media screen and (width greater than height){}

or

@media screen and (height less than width){}

For what is stated in the syntax specification it's not possible to use 'media_feature' as values. Is there any workaround WITHOUT using JavaScript? The closest thing I could get was using aspect-ratio but it was not functional.

Thanks.


回答1:


You can use an orientation media query:

@media all and (orientation:portrait) { … }
@media all and (orientation:landscape) { … }

From the W3C media Queries spec:

The ‘orientation’ media feature is ‘portrait’ when the value of the ‘height’ media feature is greater than or equal to the value of the ‘width’ media feature. Otherwise ‘orientation’ is ‘landscape’.

But note that it usually make more sense to worry about the actual width than the orientation, see this article on QuirksBlog for details.




回答2:


@N3dst4 's answer only works if your comparison is 1:1. If you are looking for a something else, you can use aspect-ratio:

@media screen and (max-aspect-ratio:4/3) {
  #bg {
    width: auto;
    height: 100%;
  }
}

@media screen and (min-aspect-ratio:4/3) {
  #bg {
    width: 100%;
    height: auto;
  }
}

I used the above snippet to properly scale a 4:3 background image.




回答3:


Second hit on google: http://css-tricks.com/6731-css-media-queries/

First part of the example in that page:

<link rel='stylesheet' media='screen and (min-width: 701px) and (max-width: 900px)' href='css/medium.css' />

Using max-width or max-height is the same as "height less than" etc..

The same goes for height.



来源:https://stackoverflow.com/questions/8355244/how-can-i-detect-which-window-dimension-is-bigger-just-using-css-media-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!