2

I have the following markup: (simplified)

<meta name="viewport" content="width=device-width, initial-scale=1.0">
...
<body>
  <div class="wrapper">
    <div class="content"> (absolutely positioned stuff) </div>
  </div>
</body>

with the following styles:

.wrapper {
   width: 100%;
   height: 100%;
}

.content {
  width: 640px;
  height: 640px;
  margin: 0 auto;
  position: relative;
  background-color: orange;
}

On a desktop (screens larger than 640px x 640px) my square is top and center, which looks good. On mobile portrait, my square is top and fills the width, which is also good and perfectly acceptable. On mobile landscape (screens less than 640px tall), however, my square fills the entire width and the user will need to scroll to see the bottom of the square, which is not acceptable.

What I'd like to achieve is for the square to fit the height of the screen so it can be seen in its entirety in landscape view. I'm trying some media queries out now to see if that helps. Otherwise, what would be the best way to achieve this?

I've tried changing .content to height: 100%, but because most of its contents are absolutely positioned they end up having 0px height. As such, ideally the square should still be 640px x 640px in size, just scaled to fit the screen so the contents can stay put.

Thanks.

irot
  • 592
  • 1
  • 6
  • 13

1 Answers1

1

This is the ideal case for viewport units. Where 100vw is the the width of the viewport, and 100vh is the height of the viewport.

You should be able to find some more information on the different units here.

One thing to note though, is that using height related viewport units can lead to some odd effects on Mobile Safari and Mobile Chrome, because the viewport height can change on scroll. The various behaviours of Chrome and Safari on mobile with regards to this have changed over the years as they try to figure you out an ideal solution. I find if I need to rely on vh units I often use a little bit of javascript or css to then "lock" the object at that height on mobile.

You can find other tips for that issue if you run into it in this Stack Overflow Post

Community
  • 1
  • 1
charrondev
  • 1,129
  • 2
  • 9
  • 13