1

I am trying to make a linear-gradient with percentage breakpoints while using "background-attachment: fixed". It is not working as I expected.

I've made a very simple fiddle about my question.

https://jsfiddle.net/f8v1h0ac/

HTML

<body>
    <header>
        Header
    </header>
    <main>
        Main
    </main>
</body>

CSS

body {
  margin: 0;
  padding: 0;
}

header {
  width: 100%;
  height: 300px;
  background-attachment: fixed;

  /* background-image: linear-gradient(to bottom, black 0px, white 300px); */

  /* The code above is working but the code below is not. Note that the color at the bottom line of header is supposed to be white. */

  background-image: linear-gradient(to bottom, black 0%, white 100%);
}

main {
  height: 2000px;
}

PS: I guess this happens because the gradient's height is respective to the window height. But I don't have a clue how to solve this problem.

ozanilbey
  • 13
  • 4
  • What is the difference between what you are expecting and what is actually happening. – Dale Oct 21 '17 at 21:17
  • Uncomment the background-image css line above, and comment the background-image css line below to see the difference. – ozanilbey Oct 21 '17 at 21:21
  • The problem is `background-attachment: fixed` makes the background size relative to the whole viewport. That's why it works when you use pixels and not percent. – agrm Oct 21 '17 at 21:23
  • Yes, I thought that was the problem, too. I still need a solution, though. – ozanilbey Oct 21 '17 at 21:26
  • Obviously :o) Unfortunately I think your best solution, given the HTML and CSS provided, is to either set the gradient using pixels or remove the whole `background-attachment: fixed`. – agrm Oct 21 '17 at 21:29
  • I have to have these. So I think I will do something that I hate: Check the header height using JS and write dynamically in pixels. – ozanilbey Oct 21 '17 at 21:31
  • My device height is 1440px and there is a huge difference. It's dark gray instead of white. – ozanilbey Oct 21 '17 at 21:33
  • By the way, what's the reason you need `background-attachment: fixed`? – agrm Oct 21 '17 at 21:42
  • Design concerns. It would take too much time to tell since I cannot demo my original work here. – ozanilbey Oct 21 '17 at 21:51

1 Answers1

0

Would this work for you? I put the header content inside a div.

header { 
  height: 300px;
  background-attachment: fixed;
}
div {
  width: 100%;
  height: 100%;  
  background-image: linear-gradient(to bottom, black 0%, white 100%);
}

https://jsfiddle.net/wazz/xkgkam74/

wazz
  • 4,953
  • 5
  • 20
  • 34