How to make CSS a Linear-Gradient that has PX values and % at the same time?

Asked

Viewed 73 times

1

I have a situation which is this, I have a linear-gradiente in one element, but I want the first and last part of that gradient to have 100px of one color, and the middle of it to always be 100% completed by another color.

To make this image clearer. Note that using only 10% 90% 10%, if the element is of different widths the width of the "column" of the left and direct will change of proportion.

inserir a descrição da imagem aqui

What I wanted was 100px 100% 100px, with a fixed value that should not change if the element is wider or narrower...

inserir a descrição da imagem aqui

So how do I merge values into PX and % within the gradient so as to have the first and last part with values in PX which will not vary according to width, but with the middle occupying the rest of the space?

Follow the code I used in the examples:

.box {
    width: 50%;
    height: 100px;
    border: 1px solid #000;
    background-image: linear-gradient(to right, red 10%, blue 10%, blue 90%, red 90%);
}
.box:nth-child(2) {
    width: 25%;
}
<div class="box"></div>
<div class="box"></div>

1 answer

2


As I did not have an answer, I will post the solution I arrived to solve the problem.

I used a calc(), in the middle color of the gradient to determine which size it would be 100% - 50px, where 50px and the width that I would like to have in the last part of the gradient. That way I got two "columns" of fixed size, as they are not in %, with percentage values the width of the "columns" varied according to the width of the container.

The result was so inserir a descrição da imagem aqui

Code as shown above:

.box {
    width: 50%;
    height: 100px;
    border: 1px solid #000;
    background-image: linear-gradient(to right,red 50px, blue 50px, blue calc(100% - 50px), red calc(100% - 50px))
}
.box:nth-child(2) {
    width: 25%;
}
<div class="box"></div>
<div class="box"></div>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.