开发者

PHP version of CSS Media Queries

开发者 https://www.devze.com 2023-02-22 18:36 出处:网络
Can\'t find anything on the web for this, wanted to throw the question out there. Is the a PHP versi开发者_StackOverflowon of CSS Media Queries? I\'m under the assumption that you would want to do th

Can't find anything on the web for this, wanted to throw the question out there.

Is the a PHP versi开发者_StackOverflowon of CSS Media Queries?


I'm under the assumption that you would want to do this for the purpose of detecting mobile browsers - if not, then this answer is slightly irrelevant.

You can check out Mobile ESP for a mobile User Agent detection library. It's very simple to use and works well in my experiences.


No, there isn't.

The browser doesn't send information on any of its media features to the server, so PHP doesn't have the information needed to implement this.


I've used a method (found on http://php.net/manual/en/faq.html.php Example #4) that combines javascript and php to achieve an alternative for media queries. I achieve this by using javascript embedded inside my php to post a variable (screen.width) that is then used by php to determine breakpoints for loading stylesheets. Include the following snippet into your head tag:

<?php
  if (isset($_GET['width'])) {
    $width = $_GET['width'];
    if ($width <= 480) { //mobile devices
      $style = '<link rel="stylesheet" href="mobile.css" type="text/css">';
    } elseif ($width <= 720){ //tablets
      $style = '<link rel="stylesheet" href="tablet.css" type="text/css">';
    } else { //desktops
      $style = '<link rel="stylesheet" href="desktop.css" type="text/css">';
    }
    echo $style;
  } else {
      echo "<script language='javascript'>\n";
      echo "  location.href=\"${_SERVER['SCRIPT_NAME']}?${_SERVER['QUERY_STRING']}" . "&width=\" + screen.width; \n";
      echo "</script>\n";
      exit();
  }
?>

I found using this method was also more efficient on the content load of a page, unlike media queries (which will load the CSS styles for all devices even when it's not necessary - ie mobile devices still get desktop styles loaded). This method ensures that stylesheets get loaded specific to the device alone, assuming you have a stylesheet that has common styling for all media devices.


You may be able to check out $_SERVER['HTTP_USER_AGENT'] and make a decision based on what you find there. There may be a library out there somewhere that's already taken care of this, but I'm not aware of one off the top of my head.


There is the get_browser php function you can use to determine some browser capabilities. But that's not the same like the media queries. The css media queries are conditional to the devices display measurements. The php function does not return such informations.

0

精彩评论

暂无评论...
验证码 换一张
取 消