Как сделать бордер градиентом
Перейти к содержимому

Как сделать бордер градиентом

  • автор:

Как задать градиент для border в CSS?

Как задать градиент для border в CSS?

Рассмотрим как задать в CSS border gradient, это позволит вам создать на своём сайте красивый эффект градиентной рамки. В одной из предыдущих статей я подробно рассматривала как задать градиент в качестве фона.

Так вот, CSS 3 позволяет нам это сделать не только для фона, но и для рамки.

Навигация по статье:

Линейный градиент

Для примера рассмотрим такой блок:

Чтобы задать ему размеры, отступы и так далее я допишу следующие CSS свойства:

Теперь нам нужно задать толщину рамки и её тип:

Для задания градиента допишем свойство border-image в css файле:

Здесь мы в скобках задаём значения цветов, которые будут идти сверху вниз.
Чтобы наше CSS свойство работало во всех браузерах допишем кроссбраузерные префиксы:

И последнее зададим CSS свойство:

Чтобы заданный градиент сместился или растянулся по всей границе.
В итоге весь CSS код задания border gradient будет выглядеть так:

Вот результат работы кода:

Особенности border gradient в CSS

  1. 1 В скобках мы можем задать не обязательно 2 цвета, их может быть больше. Для этого просто указываем значения цветов через запятую:

Направление градиента border gradient

Чтобы наш градиент для рамки шел не сверху вниз, а например, слева направо или по диагонали мы можем задать для него направление при помощи дополнительных параметров.

Параметры border gradient css

При задании градиента с кроссбраузерными префиксами этот пример пишется немного иначе.

В первом случае мы писали в каком направлении должен распространяться градиент, а во втором – куда он должен идти.
Пример для border gradient слева направо:

Градиентные границы в CSS

Доброго времени суток уважаемые хабровчане. Представляю вашему вниманию перевод статьи Криса Коера.

Допустим, вам нужна градиентная граница вокруг определенного элемента. И вы, такой, думаете:

  • Для этого не существует простого и очевидного CSS API.
  • Я просто сделаю элемент-обертку с линейно-градиентным фоном, а затем внутренний элемент заблокирует большую часть этого фона, за исключением тонкой линии заполнения вокруг него.

Выглядеть это будет как-то так:

Если вам не нравится идея оберточного элемента, вы можете использовать псевдоэлемент, до тех пор, пока отрицательное значение z-индекса в порядке (этого не произошло бы, если бы было много вложений родительских элементов с их собственными фонами).

Вот пример Стивена Шоу, закрепляющий border-radius :

Но не забывайте полностью о border-image , возможно, самом бестолковом свойстве CSS всех времен. Вы можете использовать его, чтобы получить градиентные границы даже на отдельных сторонах:

Использование как border-image , так и border-image-slice , вероятно, является самым простым синтаксисом для создания градиентной границы, но, к сожалению, это просто несовместимо с border-radius .

Gradient borders

I’m trying to apply a gradient to a border, I thought it was as simple as doing this:

But this does not work.

Does anyone know what is the correct way to do border gradients?

21 Answers 21

The border-image property can accomplish this. You’ll need to specify border-style and border-width too.

instead of borders, I would use background gradients and padding. same look, but much easier, more supported.

a simple example:

EDIT: You can also leverage the :before selector as @WalterSchwarz pointed out:

Aakash's user avatar

border-image-slice will extend a CSS border-image gradient

This (as I understand it) prevents the default slicing of the "image" into sections — without it, nothing appears if the border is on one side only, and if it’s around the entire element four tiny gradients appear in each corner.

Mozilla currently only supports CSS gradients as values of the background-image property, as well as within the shorthand background.

Try this, works fine on web-kit

Joseph Sible-Reinstate Monica's user avatar

GibboK's user avatar

You can achieve this without removing the border radius with background, background-clip, and background-origin:

Basically, this positions the white background over the gradient background, clips the white background from the inner border, and clips the gradient background from the outer border. This is why you need to define the border as solid transparent .

Credit to Method 2 from this dev.to post.

It’s a hack, but you can achieve this effect in some cases by using the background-image to specify the gradient and then masking the actual background with a box-shadow. For example:

Try the below example:

NDBoost's user avatar

The most straight forward way is to use border-image property. You can use whatever linear-gradient or repeat-gradient you want. The border-image slice property needs to be 1 for linear gradient.

chandraprakash-dev's user avatar

Try this, it worked for me.

The link is to the fiddle https://jsfiddle.net/yash009/kayjqve3/1/ hope this helps

Yash009's user avatar

Webkit supports gradients in borders, and now accepts the gradient in the Mozilla format.

Firefox claims to support gradients in two ways:

IE9 has no support.

I agree with szajmon. The only problem with his and Quentin’s answers is cross-browser compatibility.

Example for Gradient Border

Using border-image css property

Another hack for achieving the same effect is to utilize multiple background images, a feature that is supported in IE9+, newish Firefox, and most WebKit-based browsers: http://caniuse.com/#feat=multibackgrounds

For example, suppose you want a 5px-wide left border that is a linear gradient from blue to white. Create the gradient as an image and export to a PNG. List any other CSS backgrounds after the one for the left border gradient:

You can adapt this technique to top, right, and bottom border gradients by changing the background position part of the background shorthand property.

Gradient Borders in CSS

Let’s say you need a gradient border around an element. My mind goes like this:

  • There is no simple obvious CSS API for this.
  • I’ll just make a wrapper element with a linear-gradient background, then an inner element will block out most of that background, except a thin line of padding around it.

Perhaps like this:

If you hate the idea of a wrapping element, you could use a pseudo-element, as long as a negative z-index value is OK (it wouldn’t be if there was much nesting going on with parent elements with their own backgrounds).

Here’s a Stephen Shaw example of that, tackling border-radius in the process:

You could even place individual sides as skinny pseudo-element rectangles if you didn’t need all four sides.

But don’t totally forget about border-image , perhaps the most obtuse CSS property of all time. You can use it to get gradient borders even on individual sides:

Using both border-image and border-image-slice is probably the easiest possible syntax for a gradient border, it’s just incompatible with border-radius , unfortunately.

DigitialOcean documents the same approach in another tutorial.

Comments

These are all great solutions, but I really hope in the near future linear-gradient on borders will be a reality. Would really help when making CSS graphics.

Yes, it was intended that you could use linear-gradient and border-image together. If you need rounded borders too, you should be able to do that with SVG and border image. I’ve successfully done that before without distorting the corners or anything. Let me know if you want me to post an example.

I’m sure everyone would enjoy having a demo like that to reference, including me!

When we were designing how border-image should work (many years ago), the thought was that the image would contain whatever rounded or fancy corners you wanted, and border-radius would only be used as a fallback, not as something that further clipped the corners.

yep i agree I would of done the same thing as well.

Wasn’t working for me on Firefox 64 until I changed the border-image to border-image-source as border-image-slice: 1 was being overridden in the cascade.

Funnily enough, browser support seems to be inconsistent for the last example. When border-image-slice is declared in advance and there’s no value for slice set in the border-image shorthand, as in the example above, Firefox 64 and Safari on iOS 12 uses the default slice value (which is 100%, resulting in border-image: <image> 100%; ) while Chrome 71 and Opera cascades the previously declared value into the shorthand (which gives border-image: <image> 1; ).

Shorthands do normally reset the longhands to their initial values when left out, so I don’t know why Chrome and Opera wouldn’t. The last example seems to be fixed in iOS12 by changing border-image to border-image-source in those two classes.

Looks much like a Chromium bug in the cascade. Interestingly, Chrome DevTools in both “Styles” and “Computed” tabs displays the value 1 of border-image-slice struck-through, and Computed styles tab shows the value 100% coming from the shorthand declaration as overriding it — as it should be — but the value 1 appears to somehow mysteriously “survive” this overriding.

As a side note, I disagree that border-image (as well as its longhand sub-properties) is “obtuse”. It’s arguably the most misunderstood CSS properties of all time, and maybe significantly underrated, especially in combination with SVG images. Some of its abilities like 9-slice scaling and — especially — painting things outside the element’s box (via border-image-outset ) are unique in CSS, and can provide much shorter and cleaner solutions to many cases that otherwise would require hacking around pseudo-elements or even extra markup.

Not sure about the last two. I’m getting different results in iOS Safari. I’d give it a look.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *