Search code examples
htmlcssresponsive-designlinear-gradients

How to align the ends of angled linear gradiant of 2 div one below other in diff. resolution


I am trying to align the end of linear gradient at top with the start of one below it. Refer the fiddle https://jsfiddle.net/poqfa2kg/

Here I want to align the end of top ( green ) with the start of Bottom( red) for any resolution, currently it breaks if I change the browser width( resize) . Is there a way to achieve this

CSS

.top{
  height: 40px;
  width: 100%;
  background: linear-gradient(78deg, red 50%, transparent 1%); 
}


.bottom{
  height: 40px;
  width: 100%;
  background: linear-gradient(78deg, green 52%, transparent 1%); 
}

HTML


<div class='top'>
  TOP
</div>

<div class='bottom'>
  BOTTOM
</div>

Should looks like this for any screen width enter image description here


Solution

  • since your height is fixed, keep the same gradient and do some calculation to add an offset the first gradient:

    .top{
      height: 40px;
      background: linear-gradient(78deg, red 50%, transparent 0) -8.5px 0 no-repeat; 
      /* 8.5px = 40px / tan(78deg) */
    }
    
    
    .bottom{
      height: 40px;
      background: linear-gradient(78deg, green 50%, transparent 0); 
    }
    <div class='top'>
      TOP
    </div>
    
    <div class='bottom'>
      BOTTOM
    </div>

    Or do it differently using skew transformation and you don't need to do any calculation and it will work with any height and angle

    [class] {
      position:relative;
      z-index:0;
      overflow:hidden;
    }
    [class]::before {
      content:"";
      position:absolute;
      z-index:-1;
      top:0;
      left:-20%;
      right:50%;
      bottom:0;
      transform:skewX(10deg); /* any angle here */
    }
    
    .top{
      height: 60px;
    }
    .top::before {
      background:red;
      transform-origin:bottom; /* bottom here */
    }
    
    .bottom{
      height: 40px;
    }
    
    .bottom::before {
      background:green;
      transform-origin:top; /* top here */
    }
    <div class='top'>
      TOP
    </div>
    
    <div class='bottom'>
      BOTTOM
    </div>