How to apply different CSS for mobile devices not just based on media width/height

ぐ巨炮叔叔 提交于 2019-12-13 18:23:15

问题


I want to show different CSS styles for some elements just for mobile devices, phones and tablets, but media queries with different widths do not work quite good just because let's say my phone and my 17" laptop both have the same full HD resolution and modern tablets have resolution bigger than most desktop monitors have...

So I want to apply CSS styles for android, iphone/ipad, blackberry, windows mobile devices that are phones/tablets.

Are there any ways?


回答1:


if ((getResources().getConfiguration().screenLayout & 
Configuration.SCREENLAYOUT_SIZE_LARGE) == Configuration.SCREENLAYOUT_SIZE_LARGE ||
(getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_XLARGE)
    ==          Configuration.SCREENLAYOUT_SIZE_XLARGE ){
        System.out.println('In Tablet');
    }else {
        System.out.println('In Phone');
    }



回答2:


Media queries can not only use width. You can also use the orientation and even the device pixel ratio. So if you address something like a retina display then you can write it more or less as follows:

@media only screen 
   and (min-device-width : xxx px) 
   and (max-device-width : xxx px) 
   and (orientation : landscape or portrait)
   and (min-resolution: xxx dpi){ 

   // your css goes here

}

Take a look for a webkit specific example here!




回答3:


One thing you can do is apply custom classes to the html element or body element using javascript by testing the userAgent.

see below:

What is the best way to detect a mobile device in jQuery?. So your solution would look something like this.

JS

/*
see the link above for other user agents. 
you could come up with a bit more sophisticate solution 
I'm sure but this would be a quick implementation.
*/
<script type="text/javascript">

//test if droid


if( /Android/i.test(navigator.userAgent) ) {
    $('body').addClass('device_android');
}

</script>

CSS

<style>

//css styles for android

.device_android element #id .orclass {
    //some styles for android specific styling here
}

</style>

Keep in mind though this targets the general device this does not address the variation in os version and browser etc. which in many cases proves to be the cause of js and css bugs.



来源:https://stackoverflow.com/questions/19809310/how-to-apply-different-css-for-mobile-devices-not-just-based-on-media-width-heig

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