Harvester
Harvester

Reputation: 15

How to set inverse gradient in a single row

I have fixed a similar problems with diagonal gradient. Now it's difficult with linear.

I was able to create a gradiet with a cross

background: linear-gradient(to right, transparent 40%,#f00 50%,transparent 60%), 
            linear-gradient(to bottom, #fff 20%,#f00 50%,#fff 80%);

I can't create a gradient that have in the left half a gradient to bottom WHITE-RED and in the right half an inverse gradient RED-WHITE.

The below is the way I had tried to create it:

background: linear-gradient(to bottom, transparent 50%,#ff0 100%), 
            linear-gradient(to right, transparent 50%,#f00 100%);

But the yellow part is full! How can I fix this situation?

This is what I want:

enter image description here

Upvotes: 1

Views: 327

Answers (2)

Cedric Reichenbach
Cedric Reichenbach

Reputation: 9319

Edit: It is possible with one background, see Harry's answer.

It's not directly possible with a single background rule on your element, but you can utilize the ::before and ::after pseudo elements.

div {
  width: 100%;
  height: 50px;
  border: 1px solid black;
  position: relative;
  background: linear-gradient(to bottom, red 0%, #ff0 100%);
}
div::before {
  content: "";
  position: absolute;
  left: 50%;
  right: 0;
  top: 0;
  bottom: 0;
  background: linear-gradient(to top, red 0%, #ff0 100%);
}
<div></div>

Upvotes: 1

Harry
Harry

Reputation: 89770

It is very much possible to achieve this using a single element and a single background rule. Just give each of the gradients 50% size of the container in the X-axis, position one gradient on the left side and the other on right side using background-position and stop the gradient from repeating by setting the value for background-repeat as no-repeat.

div {
  height: 100px;
  background: linear-gradient(to top, red 10%, yellow 50%), linear-gradient(to bottom, red 10%, yellow 50%);
  /* background-size: 50% 100%; Ideally this should be enough but it leaves a white line in the middle in snippet for some reason and so use below setting */
  background-size: 50% 100%, calc(50% + 1px) 100%;
  background-position: 0% 0%, 100% 0%;
  background-repeat: no-repeat;
}
<div></div>

Upvotes: 2

Related Questions