mathbike
mathbike

Reputation: 162

How do you make a linear gradient background image fill the entire screen on mobile?

Setup:

:root {
    background-image: linear-gradient(180deg, cadetblue, cornflowerblue);
}
body {
    height: 100vh;
    width: 100%;
}

The problem is that on mobile browsers (chrome, safari) in landscape mode the linear gradient background image does not fill the entire screen. There are white bars on the top and bottom when you scroll:

enter image description here enter image description here

If you use a solid background color on the html tag and put the linear gradient in the body tag then the solid color does fill the entire screen:

:root {
    background: cornflowerblue;
}
body {
    background-image: linear-gradient(180deg, cadetblue, cornflowerblue);
    height: 100vh;
    width: 100%;
}

But then the linear gradient background is cut off, which is not what I want.

I have tried background-attachment and background-size but those don't seem to work. I've also tried moving the height and width around but that also doesn't work. Any help would be appreciated.

Upvotes: 2

Views: 283

Answers (2)

Kyle
Kyle

Reputation: 58

I had the same issue. A fix and a more comprehensive explanation can be found here by @Tim Wickstrom.

To fix this:

Add the following CSS attribute to your html tag:

html { 
  padding: env(safe-area-inset);
}

Then add the following parameter: "viewport-fit=cover" to your meta viewport tag

<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">

This code explicitly tells the device to fill all available regions.

Upvotes: 1

arifulsajib
arifulsajib

Reputation: 297

Set the margin and padding of both html and body elements to zero, which should help in eliminating the white bars:

:root {
    background-image: linear-gradient(180deg, cadetblue, cornflowerblue);
}

html, body {
    margin: 0;
    padding: 0;
    height: 100vh;
    width: 100%;
}

Edited:

As you said in reply that the above code doesn't work for you. then you can try this.

:root {
  background: cadetblue; /* Fallback color for browsers that don't support background-attachment: fixed */
}

html,
body {
  height: 100%;
  margin: 0;
  padding: 0;
}

body {
  background-image: linear-gradient(180deg, cadetblue, cornflowerblue);
  background-attachment: fixed;
}

OR this one (Personally not recommended):

:root {
  background: linear-gradient(180deg, cadetblue, cornflowerblue);
}

body {
  margin: 0; /* Remove default margin */
  height: 100vh;
  width: 100%;

  /* push all elements to top and bottom */
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

Upvotes: 0

Related Questions