[android] scale fit mobile web content using viewport meta tag

I'm trying to figure out how to leverage the mobile viewport meta tag to automatically zoom the contents of a HTML page to fit into a web view.

Constraints:

  • The HTML may or may not have fixed size elements (ex img has a fixed width of 640). In other words I don't want to force the content to be fluid and use %'s.
  • I do not know the size of the webview, I just know its aspect ratio

For example, if I have a single image (640x100px) I want the image to zoom out if the webview is 300x250 (scale down to fit). On the other hand, if the webview is 1280x200 I want the image to zoom in and fill the webview (scale up to fit).

After reading the android docs and the iOS docs on viewports, it seems simple: since I know the width of my content (640) I just set the viewport width to 640 and let the webview decide if it needs to scale the content up or down to fit the webview.

If I put the following into my android/iPhone browser OR a 320x50 webview, the image does not zoom out to fit the width. I can scroll the image to the right and left..

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <title>Test Viewport</title>
    <meta name="viewport" content="width=640" />
    <style type="text/css">
    html, body {
      margin: 0;
      padding: 0;
      vertical-align: top;
    }

    h1,h2,h3,h4,h5,h6,p,blockquote,pre,a,abbr,acronym,address,cite,code,del,dfn,em,img,q,s,samp,small,strike,strong,sub,sup,tt,var,dd,dl,dt,li,ol,ul,fieldset,form,label,legend,button,table,caption,tbody,tfoot,thead,tr,th,td 
    {
      margin: 0;
      padding: 0;
      border: 0;
      font-weight: normal;
      font-style: normal;
      font-size: 100%;
      line-height: 1;
      font-family: inherit;
      vertical-align: top;
    }       
    </style>
  </head>
  <body>
    <img src="http://www.dmacktyres.com/img/head_car_tyres.jpg">
  </body>
</html>

What am I doing wrong here? Does the viewport meta tag only zoom into content that is < the webview area?

This question is related to android iphone ios mobile viewport

The answer is


Try adding a style="width:100%;" to the img tag. That way the image will fill up the entire width of the page, thus scaling down if the image is larger than the viewport.


In the head add this

//Include jQuery
<meta id="Viewport" name="viewport" content="initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no">

<script type="text/javascript">
$(function(){
if( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) {
  var ww = ( $(window).width() < window.screen.width ) ? $(window).width() : window.screen.width; //get proper width
  var mw = 480; // min width of site
  var ratio =  ww / mw; //calculate ratio
  if( ww < mw){ //smaller than minimum size
   $('#Viewport').attr('content', 'initial-scale=' + ratio + ', maximum-scale=' + ratio + ', minimum-scale=' + ratio + ', user-scalable=yes, width=' + ww);
  }else{ //regular size
   $('#Viewport').attr('content', 'initial-scale=1.0, maximum-scale=2, minimum-scale=1.0, user-scalable=yes, width=' + ww);
  }
}
});
</script>

ok, here is my final solution with 100% native javascript:

<meta id="viewport" name="viewport">

<script type="text/javascript">
//mobile viewport hack
(function(){

  function apply_viewport(){
    if( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent)   ) {

      var ww = window.screen.width;
      var mw = 800; // min width of site
      var ratio =  ww / mw; //calculate ratio
      var viewport_meta_tag = document.getElementById('viewport');
      if( ww < mw){ //smaller than minimum size
        viewport_meta_tag.setAttribute('content', 'initial-scale=' + ratio + ', maximum-scale=' + ratio + ', minimum-scale=' + ratio + ', user-scalable=no, width=' + mw);
      }
      else { //regular size
        viewport_meta_tag.setAttribute('content', 'initial-scale=1.0, maximum-scale=1, minimum-scale=1.0, user-scalable=yes, width=' + ww);
      }
    }
  }

  //ok, i need to update viewport scale if screen dimentions changed
  window.addEventListener('resize', function(){
    apply_viewport();
  });

  apply_viewport();

}());
</script>

For Android there is the addition of target-density tag.

target-densitydpi=device-dpi

So, the code would look like

<meta name="viewport" content="width=device-width, target-densitydpi=device-dpi, initial-scale=0, maximum-scale=1, user-scalable=yes" />

Please note, that I believe this addition is only for Android (but since you have answers, I felt this was a good extra) but this should work for most mobile devices.


Adding style="width:100%;max-width:640px" to the image tag will scale it up to the viewport width, i.e. for larger windows it will look fixed width.


I had same problem as yours, but my concern was list view. When i try to scroll list view fixed header also scroll little bit. Problem was list view height smaller than viewport (browser) height. You just need to reduce your viewport height lower than content tag (list view within content tag) height. Here is my meta tag;

<meta name="viewport" content="width=device-width,height=90%,  user-scalable = no"> 

Hope this will help.Thnks.


I think this should help you.

<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0">

Tell me if it works.

P/s: here is some media query for standard devices. http://css-tricks.com/snippets/css/media-queries-for-standard-devices/


Examples related to android

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How to implement a simple scenario the OO way My eclipse won't open, i download the bundle pack it keeps saying error log getting " (1) no such column: _id10 " error java doesn't run if structure inside of onclick listener Cannot retrieve string(s) from preferences (settings) strange error in my Animation Drawable how to put image in a bundle and pass it to another activity FragmentActivity to Fragment A failure occurred while executing com.android.build.gradle.internal.tasks

Examples related to iphone

Detect if the device is iPhone X Xcode 8 shows error that provisioning profile doesn't include signing certificate Access files in /var/mobile/Containers/Data/Application without jailbreaking iPhone Certificate has either expired or has been revoked Missing Compliance in Status when I add built for internal testing in Test Flight.How to solve? cordova run with ios error .. Error code 65 for command: xcodebuild with args: "Could not find Developer Disk Image" Reason: no suitable image found iPad Multitasking support requires these orientations How to insert new cell into UITableView in Swift

Examples related to ios

Adding a UISegmentedControl to UITableView Crop image to specified size and picture location Undefined Symbols error when integrating Apptentive iOS SDK via Cocoapods Keep placeholder text in UITextField on input in IOS Accessing AppDelegate from framework? Autoresize View When SubViews are Added Warp \ bend effect on a UIView? Speech input for visually impaired users without the need to tap the screen make UITableViewCell selectable only while editing Xcode 12, building for iOS Simulator, but linking in object file built for iOS, for architecture arm64

Examples related to mobile

How to center a component in Material-UI and make it responsive? NullPointerException: Attempt to invoke virtual method 'int java.util.ArrayList.size()' on a null object reference Asus Zenfone 5 not detected by computer background: fixed no repeat not working on mobile Check box size change with CSS onClick not working on mobile (touch) Sharing link on WhatsApp from mobile website (not application) for Android Bootstrap 3 Slide in Menu / Navbar on Mobile How to create a link for all mobile devices that opens google maps with a route starting at the current location, destinating a given place? Using form input to access camera and immediately upload photos using web app

Examples related to viewport

disable viewport zooming iOS 10+ safari? Get viewport/window height in ReactJS What does the shrink-to-fit viewport meta attribute do? What is initial scale, user-scalable, minimum-scale, maximum-scale attribute in meta tag? Mobile overflow:scroll and overflow-scrolling: touch // prevent viewport "bounce" Overflow-x:hidden doesn't prevent content from overflowing in mobile browsers Disable Pinch Zoom on Mobile Web scale fit mobile web content using viewport meta tag div with dynamic min-height based on browser window height What's the point of 'meta viewport user-scalable=no' in the Google Maps API