简体   繁体   中英

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

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?

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 !

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');
    }

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM