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.
border с градиентом и скругленными углами css
Понадобилось мне тут, по воле дизайнера, верстать округлые кнопки с градиентной обводкой.
Да, в CSS3 конечно существует «border-image», при помощи которого можно делать градиенты для рамок. Но проблема в том, что данное CSS свойство, не работает в паре со свойством border-radius, отвечающим за скругление углов.
Есть еще варианты с имитацией бордера через псевдо-элементы или дополнительные теги. Но c псевдо элементами возникают нюансы с бэкграундами. А засорять код дополнительными тегами не хотелось.
Впав в легкое отчаяние и занимаясь уже соседним не менее заковыристым элементом. Я вдруг придумала! Как можно воплотить border с градиентом и скругленными углами, стандартными свойствами css и всего одним тегом.
a.button border: 3px solid transparent; /*Обводка нужной толщины, но прозрачная*/ background: linear-gradient(0deg, #5E17EB 0.08%, #E5097F 155.74%); /*Нужный градиент в качестве фона*/ box-shadow: inset 0px 0px 0px 100vw #fff; /*Тень направленная внутрь контейнера, перекрывает ненужный фон и оставляет только рамку*/ border-radius: 60px; /*Скругляет углы*/ /*дальше несущественно - выравнивания и отступы какие вам нужны*/ padding: 20px; margin: 5px 0; display: inline-block; >Важно - "box-shadow" должен быть достаточного размера чтобы перекрыть фон в блоке с обводкой.
У данного решения есть 2 странности, которые я пока не нашла как побороть:
- Градиент под border получается зеркально отраженным. Поэтому на фон нужно ставить не конечный градиент, а его перевернутую версию.
- Вытекает из первой. В уголках получаются вставки другого цвета.
З.Ы. Во всех браузерах не тестировала, но по идее должно работать. Если оттестировали, пишите результаты 🙂
Делаем простым способом градиент для border на CSS, Simple Gradient Borders in CSS
Сразу приведу пару примеров, что бы могли сразу использовать… Предположим есть контейнер. Сделаем ему сверху border с градиентом на CSS:
В следующем примере border будет со всех сторон блока. Что бы в таком случае сделать градиент, понадобится немного другая конструкция CSS стилей
Можно ещё играться с направлением градиента. Например направление “to right” изменим на “to top right” и получим диагональное направление
Заметили, возле кодов цветов градиента стоят значения “0%” и “100%”? Этими цифрами можно устанавливать плавность перехода цвета к цвету, а так же смещение цветов в одну или другую сторону. Надеюсь этой информации хватит, что бы сделать любой градиент для border на чистом CSS!
Ещё статьи по теме:
- Простой шаблон для WordPress от Gravitsapa
- Закрываем от индексации технические страницы в Moguta CMS
- Простое бесплатное API погоды
- Исправляем ошибку HTTP при загрузке файлов в библиотеке WordPress
- Как сделать 301 редирект/перенаправление с одной страницы на другую, не затрагивая подкаталоги?
Оставь свой коммент
Привіт читачу! Якщо одержав тут корисну інформацію і тобі не байдуже, прошу фінансово допомогти (на їжу та обслуговування сайту). Дякую!
Как задать градиент у border и сделать его круглым
Есть кнопка и под кнопкой есть фон(картинка), нужно сделать градиент у border и сделать его круглым, и чтобы фон(картинка) была видна.
Здесь фон непрозрачный у div .
.rounded-corners-gradient-borders
Отслеживать
6,343 5 5 золотых знаков 25 25 серебряных знаков 55 55 бронзовых знаков
задан 8 мар 2018 в 17:08
53 1 1 серебряный знак 5 5 бронзовых знаков
2 ответа 2
Сортировка: Сброс на вариант по умолчанию
.rounded-corners-gradient-borders < width: 250px; padding: 15px; border-left: 2px solid #f00; border-right: 2px solid #3020ff; background-image: linear-gradient(45deg, #f00, #3020ff), linear-gradient(45deg, #f00, #3020ff); background-size: 100% 2px; background-position: 0 0, 0 100%; background-repeat: no-repeat; border-radius: 35px; text-align: center; font-weight: bold; font-family: Arial; >.img
Some text
Можно попробовать с box-shadow :
.box < width: 250px; margin: 2rem 0; background: transparent; border-radius: 25px; text-align: center; padding: 15px; >.gradient < box-shadow: -2px 0 0 2px rgba(255, 0, 0, 0.8), -2px -2px 0 2px rgba(48, 32, 255, 0.3), -2px 2px 0 2px rgba(48, 32, 255, 1), 0 -2px 0 2px rgba(48, 32, 255, 1), 0 2px 0 2px rgba(48, 32, 255, 1), 2px -2px 0 2px rgba(48, 32, 255, 1), 2px 2px 0 2px rgba(48, 32, 255, 1), 2px 0 0 2px rgba(255, 0, 0, 1); >img
Some text
Отслеживать
ответ дан 8 мар 2018 в 17:45
4,542 3 3 золотых знака 16 16 серебряных знаков 53 53 бронзовых знака
Спасибо, это очень похоже!)
9 мар 2018 в 18:48
@Maks, был рад помочь:)
9 мар 2018 в 18:51
* < box-sizing:border-box; >body < margin:0; background:linear-gradient(to right, #ddd,#cda); min-height:100vh; >.btn < display:inline-block; position:relative; padding:0 15px; text-align:center; width:200px; line-height:40px; cursor:pointer; user-select:none; font-weight:bold; >.btn__border < position:absolute; top:0; left:0; width:100%; height:100%; >.btn__border rect < fill:none; stroke:url(#gradient); stroke-width:3px; width:calc(100% - 6px); height:calc(100% - 6px); >.btn:hover rect
Кнопка Ещё кнопка
Отслеживать
ответ дан 10 мар 2018 в 7:05
10.4k 2 2 золотых знака 15 15 серебряных знаков 36 36 бронзовых знаков
- html
- css
-
Важное на Мете
Похожие
Подписаться на ленту
Лента вопроса
Для подписки на ленту скопируйте и вставьте эту ссылку в вашу программу для чтения RSS.
Дизайн сайта / логотип © 2023 Stack Exchange Inc; пользовательские материалы лицензированы в соответствии с CC BY-SA . rev 2023.11.21.1314
Нажимая «Принять все файлы cookie» вы соглашаетесь, что Stack Exchange может хранить файлы cookie на вашем устройстве и раскрывать информацию в соответствии с нашей Политикой в отношении файлов cookie.
