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

Viewed 40

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

2 Answers

The problem is one of geometry. While some dimensions are being declared relatively (the % distances and the width) the height of the elements is being declared in px.

When the viewport expands, for example, the height stays fixed but other things expand.

You'll have to do a bit of calculation depending on the angle and the height of the div that you want but this snippet (which I admit I just tried rather than having done the calculations) works and the height is defined in terms of vw units.

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


.bottom{
  height: 4.5vw;
  width: 100%;
  background: linear-gradient(78deg, green 51%,transparent 51%, transparent); 
}
<div class='top'>
  TOP
</div>

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

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>

Related