Border-gradient на CSS. Может ли кто показать?
Обычная горизонтальная полоска, серого цвета. Можно ли сделать градиент? Допустим начиная с серого переходя в белый p.s. да, признаюсь, я негодник гуглил. Есть рамки на все 4 стороны, есть JS, есть еще фон, поверх него накладываем свой фон, получается ‘как бы то, что надо’. Простых решений не видел
Отслеживать
задан 4 мар 2014 в 12:10
1,928 10 10 золотых знаков 54 54 серебряных знака 104 104 бронзовых знака
Не нужно никаких фильтров и прочего хлама. Все делается довольно легко. В этом видео дословно показано и рассказано как сделать градиент у рамки.
5 апр 2020 в 17:02
2 ответа 2
Сортировка: Сброс на вариант по умолчанию
Используйте псевдо-элементы с заливкой градиентом вместо бордеров.
.gradient-demo::before < /* Градиент */ background: #ffffff; background: -moz-linear-gradient(left, #ffffff 0%, #999999 100%); background: -webkit-gradient(linear, left top, right top, color-stop(0%, #ffffff), color-stop(100%, #999999)); background: -webkit-linear-gradient(left, #ffffff 0%, #999999 100%); background: -o-linear-gradient(left, #ffffff 0%, #999999 100%); background: -ms-linear-gradient(left, #ffffff 0%, #999999 100%); background: linear-gradient(to right, #ffffff 0%, #999999 100%); filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffff', endColorstr='#999999', GradientType=1); content: ""; display: block; /* Вместо толщины */ height: 3px; width: 100%; >
Отслеживать
ответ дан 4 мар 2014 в 12:25
19.9k 5 5 золотых знаков 44 44 серебряных знака 61 61 бронзовый знак
Пример шикарный!
4 мар 2014 в 13:08
background: rgb(30, 50, 230); background: -moz-linear-gradient(30deg, rgb(30, 50, 230) 30%, rgb(90, 140, 250) 70%); background: -webkit-linear-gradient(30deg, rgb(30, 50, 230) 30%, rgb(90, 140, 250) 70%); background: -o-linear-gradient(30deg, rgb(30, 50, 230) 30%, rgb(90, 140, 250) 70%); background: -ms-linear-gradient(30deg, rgb(30, 50, 230) 30%, rgb(90, 140, 250) 70%); background: linear-gradient(120deg, rgb(30, 50, 230) 30%, rgb(90, 140, 250) 70%);
Отслеживать
ответ дан 4 мар 2014 в 12:50
Михаил2342 Михаил2342
85 12 12 бронзовых знаков
-
Важное на Мете
Связанные
Похожие
Подписаться на ленту
Лента вопроса
Для подписки на ленту скопируйте и вставьте эту ссылку в вашу программу для чтения RSS.
Дизайн сайта / логотип © 2023 Stack Exchange Inc; пользовательские материалы лицензированы в соответствии с CC BY-SA . rev 2023.11.15.1019
Нажимая «Принять все файлы cookie» вы соглашаетесь, что Stack Exchange может хранить файлы cookie на вашем устройстве и раскрывать информацию в соответствии с нашей Политикой в отношении файлов cookie.
Как в CSS задать градиент для border?
Функции градиента работают как изображения, поэтому их надо применять там, где требуется подставить изображения. Для рамки это будет border-image , как-то так:
for ru.stackoverflow
Отслеживать
4,286 14 14 золотых знаков 42 42 серебряных знака 92 92 бронзовых знака
ответ дан 2 апр 2015 в 13:47
Alex Krass Alex Krass
17.5k 2 2 золотых знака 24 24 серебряных знака 52 52 бронзовых знака
.b-gradient < font-size: 15px; max-width: 300px; padding: 15px; margin: 25px auto; position: relative; padding-left: 15px; >.b-gradient:before < content: ''; position: absolute; top: 0; left: 0; height: 100%; width: 8px; >.b-gradient-vertical:before < background: rgb(255,0,0); /* Old browsers */ background: -moz-linear-gradient(top, rgba(255,0,0,1) 0%, rgba(255,0,0,1) 50%, rgba(0,0,255,1) 50%, rgba(0,0,255,1) 100%); /* FF3.6-15 */ background: -webkit-linear-gradient(top, rgba(255,0,0,1) 0%,rgba(255,0,0,1) 50%,rgba(0,0,255,1) 50%,rgba(0,0,255,1) 100%); /* Chrome10-25,Safari5.1-6 */ background: linear-gradient(to bottom, rgba(255,0,0,1) 0%,rgba(255,0,0,1) 50%,rgba(0,0,255,1) 50%,rgba(0,0,255,1) 100%); /* W3C, IE10+, FF16+, Chrome26+, Opera12+, Safari7+ */ filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#ff0000', endColorstr='#0000ff',GradientType=0 ); /* IE6-9 */ >.b-gradient-gorizontal:before < background: rgb(255,0,0); /* Old browsers */ background: -moz-linear-gradient(left, rgba(255,0,0,1) 0%, rgba(255,0,0,1) 50%, rgba(0,0,255,1) 50%, rgba(0,0,255,1) 100%); /* FF3.6-15 */ background: -webkit-linear-gradient(left, rgba(255,0,0,1) 0%,rgba(255,0,0,1) 50%,rgba(0,0,255,1) 50%,rgba(0,0,255,1) 100%); /* Chrome10-25,Safari5.1-6 */ background: linear-gradient(to right, rgba(255,0,0,1) 0%,rgba(255,0,0,1) 50%,rgba(0,0,255,1) 50%,rgba(0,0,255,1) 100%); /* W3C, IE10+, FF16+, Chrome26+, Opera12+, Safari7+ */ filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#ff0000', endColorstr='#0000ff',GradientType=1 ); /* IE6-9 */ >.b-gradient-radial:before< background: rgb(255,0,0); /* Old browsers */ background: -moz-radial-gradient(center, ellipse cover, rgba(255,0,0,1) 0%, rgba(255,0,0,1) 50%, rgba(0,0,255,1) 50%, rgba(0,0,255,1) 100%); /* FF3.6-15 */ background: -webkit-radial-gradient(center, ellipse cover, rgba(255,0,0,1) 0%,rgba(255,0,0,1) 50%,rgba(0,0,255,1) 50%,rgba(0,0,255,1) 100%); /* Chrome10-25,Safari5.1-6 */ background: radial-gradient(ellipse at center, rgba(255,0,0,1) 0%,rgba(255,0,0,1) 50%,rgba(0,0,255,1) 50%,rgba(0,0,255,1) 100%); /* W3C, IE10+, FF16+, Chrome26+, Opera12+, Safari7+ */ filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#ff0000', endColorstr='#0000ff',GradientType=1 ); /* IE6-9 fallback on horizontal gradient */ >
А как задать градиент к примеру для border-left: ? А как задать градиент к примеру для border-left: ? А как задать градиент к примеру для border-left: ? А как задать градиент к примеру для border-left: ? А как задать градиент к примеру для border-left: ? А как задать градиент к примеру для border-left: ?
Отслеживать
ответ дан 26 мая 2016 в 16:50
27.6k 5 5 золотых знаков 35 35 серебряных знаков 65 65 бронзовых знаков
-
Важное на Мете
Похожие
Подписаться на ленту
Лента вопроса
Для подписки на ленту скопируйте и вставьте эту ссылку в вашу программу для чтения RSS.
Дизайн сайта / логотип © 2023 Stack Exchange Inc; пользовательские материалы лицензированы в соответствии с CC BY-SA . rev 2023.11.15.1019
Нажимая «Принять все файлы cookie» вы соглашаетесь, что Stack Exchange может хранить файлы cookie на вашем устройстве и раскрывать информацию в соответствии с нашей Политикой в отношении файлов cookie.
Как задать градиент для border в CSS?

Рассмотрим как задать в CSS border gradient, это позволит вам создать на своём сайте красивый эффект градиентной рамки. В одной из предыдущих статей я подробно рассматривала как задать градиент в качестве фона.
Так вот, CSS 3 позволяет нам это сделать не только для фона, но и для рамки.
Навигация по статье:
- Линейный градиент
- Особенности border gradient в CSS
- Направление градиента border gradient
- Эффекты при наведении с использованием border gradient

Линейный градиент
Для примера рассмотрим такой блок:
Чтобы задать ему размеры, отступы и так далее я допишу следующие CSS свойства:
.border-gradient1 < width : 80px ; /**ширина блока**/ padding : 20px 40px ; /**внутренние отступы**/ text-align : center ; /**выравнивание по центру**/ color : #000 ; /**цвет текста**/
Теперь нам нужно задать толщину рамки и её тип:
border: 10px solid transparent;
Для задания градиента допишем свойство border-image в css файле:
border-image: linear-gradient(#0B0E7F , #0B95DD);
Здесь мы в скобках задаём значения цветов, которые будут идти сверху вниз.
Чтобы наше CSS свойство работало во всех браузерах допишем кроссбраузерные префиксы:
-moz-border-image: -moz-linear-gradient(#0B0E7F , #0B95DD);
-webkit-border-image: -webkit-linear-gradient(#0B0E7F , #0B95DD);
И последнее зададим CSS свойство:
border-image-slice: 1;
Чтобы заданный градиент сместился или растянулся по всей границе.
В итоге весь CSS код задания border gradient будет выглядеть так:
.border-gradient1 < border : 10px solid transparent ; border-image : linear-gradient ( #0B0E7F , #0B95DD ) ; -moz-border-image : -moz-linear-gradient ( #0B0E7F , #0B95DD ) ; -webkit-border-image : -webkit-linear-gradient ( #0B0E7F , #0B95DD ) ; border-image-slice : 1 ;
Вот результат работы кода:
Особенности border gradient в CSS
- 1 В скобках мы можем задать не обязательно 2 цвета, их может быть больше. Для этого просто указываем значения цветов через запятую:
border-image: linear-gradient(to bottom right, #DC2903 , #F4F955, #0625F9);
border-image: linear-gradient( #0E9ADF 0%, #F4F955 20%, #0625F9 100%);
-moz-border-image: -moz-linear-gradient(#0E9ADF 0%, #F4F955 20%, #0625F9 100%);
-webkit-border-image: -webkit-linear-gradient(#0E9ADF 0%, #F4F955 20%, #0625F9 100%);
Направление градиента border gradient
Чтобы наш градиент для рамки шел не сверху вниз, а например, слева направо или по диагонали мы можем задать для него направление при помощи дополнительных параметров.

При задании градиента с кроссбраузерными префиксами этот пример пишется немного иначе.
-moz-border-image: -moz-linear-gradient(left, #0B0E7F , #0B95DD);
-webkit-border-image: -webkit-linear-gradient(left, #0B0E7F , #0B95DD);
В первом случае мы писали в каком направлении должен распространяться градиент, а во втором – куда он должен идти.
Пример для border gradient слева направо:
Gradient Borders in CSS
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.
Psst! Create a DigitalOcean account and get $200 in free credit for cloud-based hosting and services.
Comments
RyanIndustries8
Permalink to comment # December 28, 2018
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.
Brad Kemper
Permalink to comment # December 28, 2018
Hey Chris, 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.
Chris Coyier
Permalink to comment # December 28, 2018
I’m sure everyone would enjoy having a demo like that to reference, including me!
Brad Kemper
Permalink to comment # December 28, 2018
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.
sonya brimecombe
Permalink to comment # January 7, 2019
yep i agree I would of done the same thing as well.
Permalink to comment # December 28, 2018
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.
Anders Grimsrud
Permalink to comment # December 28, 2018
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:
Brad Kemper
Permalink to comment # December 28, 2018
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.
Permalink to comment # January 1, 2019
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.
Joe Kotlan (@Jkotlan)
Permalink to comment # December 29, 2018
Not sure about the last two. I’m getting different results in iOS Safari. I’d give it a look.
Permalink to comment # December 29, 2018
Here is a variant with SVG: https://codepen.io/ccprog/pen/BvwbKX?editors=1100 It tries to expose as many specifics to CSS as possible. Note that SVG 2 would allow rx/ry to be defined as CSS properties, but implementation is as yet incomplete. Gradient positioning must also be done in the markup. Border positioning follows SVG rules, which means half the border overflows the box.
George W. Park
Permalink to comment # December 31, 2018
I have a pen showing how you can use background-clip to create rounded gradient borders https://codepen.io/GeorgePark/pen/EEGJEj
Permalink to comment # January 1, 2019
Thanks for writing this! I used the first option recently when a student wanted to have a gradient border animated.
Worked out pretty well: https://codepen.io/jupago/ Did not know about border-image-slice. Might also be fun to try clip-path. That 24ways article on Clip Paths got me wondering if that will eventually be the the next best thing. https://24ways.org/2018/clip-paths-know-no-bounds/
Permalink to comment # January 1, 2019
Been playing around with the Stephen Shaw’s ::before border. I tried applying it to one of my working projects and it seems that if you apply any sort of transform to the base element, then the pseudo element overrides the background color/image of the base element. I don’t know any way to make this work together with transform, just something to keep in mind, and a challenge to find a workaround.
Alex Overbeck
Permalink to comment # April 19, 2019
I was able to come up with a pretty simple, single element, solution to this using multiple backgrounds and the background-origin property.
.wrapper < background: linear-gradient(#222, #222), linear-gradient(to right, red, purple); background-origin: padding-box, border-box; background-repeat: no-repeat; /* this is important */ border: 5px solid transparent; >
The nice things about this approach are:
1. It isn’t affected by z-index
2. It can scale easily by just changing the width of the transparent border Check it out: https://codepen.io/AlexOverbeck/pen/axGQyv?editors=1100
Chris Coyier
Permalink to comment # January 31, 2022
From reader Fabian Michael:
Hi, I found another solution to the problem, based on the good old 9-slice scaling technique. The CSS is rather extensive, but it does not need any extra SVG elements in your document or any additional elements nesting and might be interesting for some of you:
Geoff Graham
Permalink to comment # November 21, 2022
Another one from reader Blaz Kemperle:
I needed a responsive button with border-gradient and radius and transparent background, and after the developers “it can’t be done” I coded it by myself.