Search code examples
htmlcssalignmentresponsivelinear-gradients

How do I align two linear gradients?


I've got two linear gradients, one below the other, and I want to have them align and stay aligned across all screen sizes.

This is what I want it to look like

This is what I want it to look like

(so you know what I mean when I say "aligned"

As I currently have it, I can align them by putting in specific percentages, but on any other screen the two gradients will be unaligned

like this.

    <div style="background-image: linear-gradient(110deg, #0085CA 54%, #e3e3e3 54%); height: 50vh;"></div>
    <div style="background-image: linear-gradient(110deg, #ffffff 45%, #000 45%); height: 50vh;"></div>

I've looked around for answers but have been unable to find anything for this specific case, so any help would be much appreciated.


Solution

  • Adjust the background-size and it will be easy. The trick is to make the gradient equal to twice the size of the element so equal to the size of both elements. Then you place one on the top and the other on the bottom

    .box {
      height: 50vh;
      background-image: linear-gradient(110deg, #0085CA 50%, #e3e3e3 50%);
      background-position: top;
      background-size: 100% 200%;
    }
    
    .box + .box {
      background-image: linear-gradient(110deg, #ffffff 50%, #000 50%);
      background-position: bottom;
    }
    
    body {
      margin: 0;
    }
    <div class="box"></div>
    <div class="box"></div>

    A gradient that you can also generate with no html element and only CSS:

    html::before {
      content:"";
      position:fixed;
      top:0;
      left:0;
      right:0;
      height: 50vh;
      padding-bottom:50vh;
      background: 
         linear-gradient(110deg, #0085CA 50%, #e3e3e3 50%) padding-box content-box,
         linear-gradient(110deg, #ffffff 50%, #000    50%);
    }

    Another idea:

    html::before {
      content:"";
      position:fixed;
      top:0;
      bottom:0;
      left:-100%;
      right:-100%;
      background: 
         linear-gradient(#e3e3e3 50%,#000    0) right/50% 100% no-repeat,
         linear-gradient(#0085CA 50%,#ffffff 0);
      transform:skew(-20deg); /* 20 = 110 - 90 */
    }

    Another one for the fun with more complex syntax:

    html{
      --s:calc(50vh * 0.363); /* this will control the  angle. 0.363 = tan(20deg)*/
      
      min-height:100%;
      background: 
         linear-gradient(to bottom right,#0085CA 50%,transparent 50.5%) calc(50% + var(--s)/2) 0,
         linear-gradient(to right, #0085CA 50.1%,#e3e3e3 0) top,
         linear-gradient(to top left    ,#000    50%,transparent 50.5%) calc(50% - var(--s)/2) 100%,
         linear-gradient(to right, #ffffff 49.9%, #000   0) bottom;
      background-size:var(--s) 50%,100% 50%;
      background-repeat:no-repeat;
    }