0

I need to load different CSS stylesheet for mobile phones, but not for tablets. I was using the following solutions in the past:

<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="viewport" content="width=480">
<link rel="stylesheet" media="only screen and (max-width: 480px)"href="mobile.css" />
<link rel="stylesheet" media="only screen and (min-width: 481px)" href="desktop.css" />

or:

@media only screen and (max-width: 480px) {
}

but both are based on screen resolutions. The most of today's mobile phones use higher resolutions so it won't work as I want and here is the reason: Tablets will also be affected by this part:

<meta name="viewport" content="width=480">

And I want tablets to act like desktops / laptops.

Also, I was trying to do it this way:

var IS_IPHONE = navigator.userAgent.match(/iPhone/i) != null;
var IS_ANDROID = navigator.userAgent.match(/Android/i)  != null;

if(IS_IPHONE)    ({
      url: href,
      dataType: 'css',
      success: function(){                  
            $('<link rel="stylesheet" type="text/css" href="'+css/iphone.css+'" />').appendTo("head");
        }
});

if(IS_ANDROID)    ({
      url: href,
      dataType: 'css',
      success: function(){                  
            $('<link rel="stylesheet" type="text/css" href="'+css/android.css+'" />').appendTo("head");
        }
});

but there are so many different phones nowadays, that I can't search for every possible device and add it once a while. Besides, Androids are also tablets nowadays.

Is there any GENERIC code which detects smartphones (not tablets, just phones)? I guess it can't be based on media queries.

I was trying to find a solution based on current posts, but there wasn't clear answer on my question, so I've posted it here.

Thanks

Piotr Ciszewski
  • 1,691
  • 4
  • 30
  • 53

1 Answers1

1

Mobile Detect is a very simple and effective PHP method of detecting devices - https://github.com/serbanghita/Mobile-Detect

In simplest terms:

/ Include and instantiate the class.
require_once 'Mobile_Detect.php';
$detect = new Mobile_Detect;

// Any mobile device (phones or tablets).
if ( $detect->isMobile() ) {

}

// Any tablet device.
if( $detect->isTablet() ){

}

// Exclude tablets.
if( $detect->isMobile() && !$detect->isTablet() ){

}

You can use composer in your release and update process to make sure you have the latest Mobile_Detect version.

composer require mobiledetect/mobiledetectlib

{
    "require": {
        "mobiledetect/mobiledetectlib": "^2.8"
    }
}
RichTea
  • 1,462
  • 10
  • 16
  • 24