background-size cover not maintaining aspect ratio, android chrome

1.9k Views Asked by At

On desktops, iPad the image in the background maintains its aspect ratio when the element has background-size: cover , but on my Android phone (chrome) the image seems to act more like width:100%;height:100%,

You can see it in action here.

Here's a screenshot from my phone

// Markup
<div class="wrapper">
  <div class="content">
...

// Style
html, body {
  height: 100%
}

.wrapper {
  position: relative;
  height: 100%;
  background-image: url(...);
  background-size: cover;
  ..vendor prefixes..
}
2

There are 2 best solutions below

0
On BEST ANSWER

I had a similar issue and it was pretty difficult to debug, but eventually I managed to find the reason: image pixel size.

TL;DR
Don't use big sized images, mobile devices don't like em, use max 2000px wide pics.


Few more details

Simply put, mobile devices can't handle big sized images, depending on model and OS. The results may vary: some may simply break, others display a blank image or distortions like the one in this question, and sometimes even return a 404 error! (been there, done that).

I've found info on this issue in many places here on SO and elsewhere on the web, a good article is this with a nice tool to calculate image size:
http://www.williammalone.com/articles/html5-javascript-ios-maximum-image-size/.

The ideal image size to use shouldn't be more than 2000px from my tests, mostly to support the largest (and oldest too) part of mobile devices, but it's recommended to test out depending on your needs.

4
On

Sometimes it helps to define the viewport for your html document:

html{
  height:100%;
  min-height:100%;
  width: 100%;
  min-width: 100%;
}
body{
  min-height:100%;
  min-width: 100%;
}

As on can i use outlined chrome for android should handle this well.

Next you could use media queries to create a workaround, because chrome on your phone does not handle the cover attribute the way it should:

/* Portrait */
@media screen and (orientation:portrait) {
    /* Portrait styles */
    .wrapper {
      background-image: url(...);
      background-size: auto 100%;
    }
}
/* Landscape */
@media screen and (orientation:landscape) {
    /* Landscape styles */
   .wrapper {
      background-image: url(...);
      background-size: 100% auto;
    }
}

This is quite simple but does a solid and good job. If you want to limit this css to be available only for smaller devices you can extend the media query like

@media screen and (orientation:landscape) and (max-width: 400px) { add css }

Hope this helps,

best regards, Marian.