D
D
Dmitry2013-08-01 22:00:12
css
Dmitry, 2013-08-01 22:00:12

Responsive layout scaling problem on mobile browsers

I started designing my first responsive website. Everything went well: block sizes in percentages, use of media queries, etc. When experimenting with the size of the browser, everything stretches, shrinks, rebuilds as it should. I uploaded the site to the server, logged in from my smartphone (android) and ran into a problem. But the topic is not even about this problem, but about another, which was generated by the solution of the first. More on that below...


Probably everyone who was involved in adaptive layout (and not only adaptive) knows that when a site is displayed on a mobile version of the browser (say, on a screen size of 480 pixels wide), the site is not displayed at a scale of 1: 1, but “shrinks” to fit the browser window. Those. the browser reduces the site to such a size that it fits entirely in the browser window. Site elements become small, fonts are not readable. And the user has to increase (scale) it manually. But I don't like this situation. I then did an adaptive layout with the hope that it would be displayed in the browser in its real size and shrink not due to scaling the page to fit the window, but precisely due to the rubberiness of the blocks. The outer block () of the site has a maximum width of 900 pixels, with the ability to shrink up to 320. Blocks inside are also compressed, are being rebuilt, etc. - it doesn't matter, because it's not about that. So, when compressing the browser window on a PC, with a window size of less than 900 pixels, the site begins to compress successfully due to the percentage sizes specified in css, media queries, etc. And when you open it on a mobile device, it remains in its real size and aspect ratio, but simply scaled to fit the browser window.

Once again, I repeat that the problem is not new, and perhaps many layout designers are familiar and maybe I’m chewing it in vain, but still, just in case, I tried to describe in detail.

And on Habré the solution to this problem has already been mentioned, and it is not difficult to google. Using the viewport meta tag

<meta name="viewport" content="width=device-width; initial-scale=1">

which tells the browser that the site should be displayed as is, not scaled automatically on initial load (then, of course, you can scale with your fingers, if you do not prohibit it in the same meta tag). And if, for example, this is not an adaptive site and its width is greater than the width of the browser window, then, of course, it will not fit entirely, the user will either need to reduce (scale manually) or scroll. And if this is an adaptive site, then, as it was intended by the layout designer, it will shrink due to the rubberiness of the blocks to the width of the window. Which is what happened to my site.

But my joy did not last long. Until I opened this page on my tablet. The width of the screen of my Samsung in horizontal orientation (and the problem arose precisely in viewing in horizontal orientation) is 1280 pixels.

What happened in the end. A site whose maximum width, let me remind you, is 900 pixels, was displayed in its normal size at 100% scale. But the screen size of the device is 1280 pixels! And what happened in the end? But it turned out that the site did not take up the entire width of the screen, but took its rightful 900 pixels. As a result, margins of approximately 154 pixels ((1280-900)/2) remained at the edges. Some will say that this is normal. After all, when we open a site on a PC, with a screen width of, say, the same 1280 pixels, then naturally the site will not occupy the entire width, but will occupy the 900 pixels assigned to it, which are set in CSS as the maximum site width (or a fixed width, if it's a fixed layout).

But on a tablet, this situation does not seem normal. Because the screen itself is still small compared to desktops, even though it has a resolution of 1280 pixels. I would like the site to take up as much space as possible on this screen. On a computer, we do not need this, because. 900 pixels on the monitor will look normal, since the pixel size is larger than that of the tablet. But on a tablet, when the page does not take up the entire screen, it seems wild (at least to me). And it's all about the viewport meta tag, which we set to display the site in real scale. This helped us when the site size was less than 900 points, ie. helped us not to scale it to the screen size, but to display it in real size. But this prevents us when the screen size is more than 900 pixels, because here we just want the scaling to work, so that the site increases to the size of the window, i.e. I used the entire width of the screen to the maximum, because this is still a mobile device.

I loaded the old version of this site for comparison (the design is exactly the same, except that it is not responsive, but fixed width of 900 pixels) and it took up the entire width of the screen on initial load. After all, I did not use the viewport in it.

In conclusion, I want to say that I have only tested it on Samsung so far. I'm afraid to guess what will happen on the iPad, whose resolution on the wide side is twice that of Samsung, 2048 pixels. Really the page will occupy less than a half of the screen (it 900 points)?

In short, I would like to ask the community if anyone has encountered similar problems. And can this be considered a problem? Or is this normal behavior that does not need to be corrected in any way? Those. the site is displayed in real scale. If it doesn’t take up the whole screen, then the client will easily enlarge it with his fingers, scale it as it should?

I tried to find a way to make it so that when the screen size is less than 900 pixels, the viewport would work, and if the size is more than 900 pixels, it would not work. Have not found.

PS I apologize that I did not post this text in q & a, I missed this moment, and now I can’t change it.

Answer the question

In order to leave comments, you need to log in

8 answer(s)
V
Valery Zinchenko, 2016-03-27
@officialmuse

Just like this:

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

L
LemaroWeb, 2014-10-23
@LemaroWeb

None of the options above helped.
The problem was that on mobile devices it was not displayed to the full width and height.
Solved this way, but based on comments and reading other questions and answers:

if (window.devicePixelRatio !== 1) { // Костыль для определения иных устройств, с коэффициентом отличным от 1		
  var dpt = window.devicePixelRatio;
  var widthM = window.screen.width * dpt;
  var widthH = window.screen.height * dpt;
  document.write('<meta name="viewport" content="width=' + widthM+ ', height=' + widthH + '">');
}

V
Vlad lo., 2014-02-05
@Voltmod

1. Check the layout right away, taking into account media queries, font scale, etc. right away, in the browser, How to test mobile layout?
2. Write media queries in the right order, with the right values, the right conditions.
stephen.io/mediaqueries

@media only screen and (min-device-width : 900px) and (max-device-width : 1280px) {
Ширина блока контейнера 100% + убрать прочие привязки в 900 px
}

M
Makito, 2013-08-01
@Makito

And why is it important for you that the site is no more than 900 pixels wide?
And don’t worry about the iPad with Retina display, if you turn off the zoom on the site, then in fact you will get the same 1024 in the landscape and not 2048.

M
m-haritonov, 2013-08-03
@m-haritonov

If I understood everything correctly, then you have content with a minimum width of 320px and a maximum width of 900px. And you need to:
1. If the device screen size is less than 900px, then set the width of the page viewport to be the same as the device screen (so that the CSS markup is rebuilt to fit this width).
2. If the device screen size is greater than or equal to 900px, then set the width of the page's viewport to 900px (so that on screens of 900px and larger, the content increases due to the scale).
For this task, I can offer the following solution (copy the JavaScript code from this example to your site, placing it above all other connections and inserts of CSS and JavaScript code). Tested only on iPad 2.

<!DOCTYPE html>
<html>
  <head>
    <script type="text/javascript">
      (function(){
        // Выполняем код только на мобильных браузерах (на всякий случай)
        if (typeof(window.orientation) !== 'undefined')
        {
          // Функция взята отсюда: https://makandracards.com/makandra/13743-detect-effective-horizontal-pixel-width-on-a-mobile-device-with-javascript
          function getDeviceWidth()
          {
            var deviceWidth = window.orientation == 0 ? window.screen.width : window.screen.height;
            // iOS returns available pixels, Android returns pixels / pixel ratio
            // http://www.quirksmode.org/blog/archives/2012/07/more_about_devi.html
            if (navigator.userAgent.indexOf('Android') >= 0 && window.devicePixelRatio)
              deviceWidth = deviceWidth / window.devicePixelRatio;

            return deviceWidth;
          }

          var deviceWidth = getDeviceWidth();
          var maxWidth = 900;
          
          if (deviceWidth < maxWidth)
          {
            // Мои эксперименты на iPad 2 показали, что device-width всегда содержит значение ширины 
            // экрана в книжной (portrait) ориентации (т.е. даже, если устройство находится в 
            // альбомной (landscape) ориентации). Это же утверждалось в некоторых найденных мною статьях.
            if (window.orientation == 0 || window.orientation == 180)
              document.write('<meta name="viewport" content="width=device-width">');
            else
              document.write('<meta name="viewport" content="width=device-height">');
          }
          else
            document.write('<meta name="viewport" content="width=' + maxWidth + '">');
        }
      })();
    </script>
    
    <style type="text/css">
      * { margin: 0; padding: 0; }
      .content { min-width: 320px; max-width: 900px; background: #ffff99; }
      .content div { border: 1px solid #f00; }
    </style>
  </head>
  <body>
    <div class="content">
      <div>
        abc abc abc abc abc abc abc abc abc abc abc abc abc abc abc abc abc abc abc abc abc
        abc abc abc abc abc abc abc abc abc abc abc abc abc abc abc abc abc abc abc abc abc
        abc abc abc abc abc abc abc abc abc abc abc abc abc abc abc abc abc abc abc abc abc
      </div>
    </div>
  </body>
</html>

H
hardhardy, 2021-03-30
@hardhardy

In my case, with a similar problem, the simple solution
html, body {width:100%; overflow-x:hidden}

S
Sergey, 2014-10-13
@zetabit

if you are talking about the wrong initial scale in the iPad, then this helped me:

<script>
  $(function() {
    if (navigator.userAgent.match(/iPhone/i) || navigator.userAgent.match(/iPad/i)) {
      var viewportmeta = document.querySelector('meta[name="viewport"]');
      if (viewportmeta) {
        viewportmeta.content = 'width=device-width, minimum-scale=1.0, maximum-scale=1.0, initial-scale=1.0';
        document.body.addEventListener('gesturestart', function () {
          viewportmeta.content = 'width=device-width, minimum-scale=0.25, maximum-scale=1.6';
        }, false);
      }
    }
  })
</script>

by default, regardless of the viewport and initial-scale=1, I still didn’t want it, oh, those iPads :-)

F
fursanton1986, 2019-10-20
@fursanton1986

it's simple, make media queries specifying the width of the window in centimeters, not pixels.
For example: media (max-width: 20cm) will allow you to separate small devices from monitors, no matter what their pixel resolutions are.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question