- Градиентный текст
- Градиент текста CSS
- Градиентная рамка
- Прозрачный текст
- Прозрачный текст с обводкой
- Интересный эффект при наведении
- Статьи из данной категории:
- Create a gradient border in CSS
- Pseudo element
- Positioning trick
- Masking trick
- Background clip
- Demo
- Let’s start
- Articles you may found Useful
- Градиентные границы в CSS
- Как задать градиент для border в CSS?
- Навигация по статье:
- Линейный градиент
- Особенности border gradient в CSS
- Направление градиента border gradient
Градиентный текст
Рассмотрим градиент для текста и рамки, сделаем текст прозрачным, а также реализуем интересный эффект при наведении.
Градиент текста CSS
На момент обновления статьи градиентный текст поддерживается более 97% браузеров с учётом -webkit- префикса.
Пример — Градиентный текст
- -webkit-background-clip — как выводиться цвету фона под границами блока,
- значение text — позволяет цвету фона распространяться только на текст нашего элемента.
Таким образом можно реализовать любой градиент для текста.
Например, используем repeating-linear-gradient .
repeating-linear-gradient(45deg, #fff, #fff 1px, #4a148c 4px);
Пример — Полосатый текст с помощью CSS
Градиентная рамка
Для создания градиентной рамки, используйте следующий код:
Пример — Градиентная рамка
Прозрачный текст
mix-blend-mode — выбор режима смешивания цветов элемента со слоями ниже. multiply — режим, при котором происходит умножение цвета текста и цвета фона, с последующей заменой фона.
Если браузер не будет поддерживать свойство, то текст будет отображён белым цветом.
Прозрачный текст с обводкой
Чтобы реализовать прозрачный текст с обводкой, поспользуемся css-свойством text-stroke :
Интересный эффект при наведении
.wow-hover < position: relative >.wow-hover::after < content: ""; position: absolute; top: 0; left: -1.5em; width: 110%; height: 100%; background: linear-gradient(to right, transparent, rgba(255,255,255,.7), transparent) no-repeat; background-position: -1em 0%; background-size: 2.5em 100%; transform: skewX(-45deg); >.wow-hover:hover::after
Надеюсь, вам понравилась данная информация. Если вам интересна тема web-разработки, то можете следить за выходом новых статей в Telegram.
Статьи из данной категории:
Create a gradient border in CSS
To show gradients for a border with CSS you can use the border-image property. It allows setting gradient values in the same way as the background-image property.
Besides the border-image property, you should specify additional properties to actually show border gradient.
We can combine these properties into a shorthand syntax border-width with border-style into border and border-image-source with border-image-slice into border-image .
.gradient-border border: 5px solid; border-image: linear-gradient(45deg, purple, orange) 1; >
Now you have a nice looking gradient border. And you can use all types of gradients: linear-gradient , radial-gradient and conic-gradient .
However, there’s a drawback to this approach. You cannot use border-radius property, as it is not supported with the border-image property. But there are a few workarounds.
Pseudo element
Positioning trick
For this approach, we need to add a gradient as a background-image for the pseudo-element. Additionally, we need to set its position to absolute and set a negative margin, that will represent the border width. Give it a negative z-index to make it below the main element. And finally, make it inherit border-radius from the main element.
For the initial element, we need to set the required border-radius . Set background color, to match the body background. Optionally we give it a margin to make it within the boundaries of the container because pseudo-element has a negative margin.
.gradient-border-pseudo position: relative; padding: 10px 20px; background: #fff; margin: 5px; border-radius: 5px; > .gradient-border-pseudo::after content: ""; position: absolute; top: 0; right: 0; bottom: 0; left: 0; z-index: -1; margin: -5px; border-radius: inherit; background-image: linear-gradient(45deg, purple, orange); >
Masking trick
For this solution, we’ll also use the pseudo-element, but instead of positioning it with z-index , we will use the mask property to clip the background.
The mask CSS shorthand property hides an element (partially or fully) by masking or clipping the image at specific points.
— MDN
While the mask property may lack full support, you can use this approach for the gradient border.
We’ll set the element’s background as a gradient. And then using mask property we’ll specify two more gradient backgrounds (same color as body ). The first one will mask (cover) the area within the padding boundaries, and the second one will mask (cover) the area all the way up to the border.
Additionally, we need to set the mask-composite property to exclude the top layer from the bottom in order to see the border.
.gradient-border-mask position: relative; padding: 15px 20px; > .gradient-border-mask::before content: ""; position: absolute; top: 0; left: 0; right: 0; bottom: 0; border-radius: 50px; border: 5px solid transparent; background: linear-gradient(45deg,purple,orange) border-box; -webkit-mask: linear-gradient(#fff 0 0) padding-box, linear-gradient(#fff 0 0); -webkit-mask-composite: destination-out; mask-composite: exclude; >
Background clip
To avoid additional styles for pseudo-element you can use the background-image property in combination with background-clip property.
The background-clip CSS property sets whether an element’s background extends underneath its border box, padding box, or content box.
— MDN
Essentially we’re going to clip the background in the similar way we did with the mask property.
First, we’ll need to pass two gradients values for the background-image . One will represent the background of the element with the according color, and the second one will represent the border with gradient.
For each of the gradients, we’ll specify the background-clip property.
For the first one, the value will be padding-box , so the background will extend up until the border.
For the second one, the value will be border-box , which means that the background will extend to the outside edge of the border.
Finally we need to specify a transparent border color and border-radius , and it’s done.
.gradient-border-bg background: linear-gradient(#fff, #fff) padding-box, linear-gradient(45deg, slateblue, coral) border-box; border: 5px solid transparent; border-radius: 50px; >
💡 NOTE: To control the inner border-radius while maintaining the gradient you should use a slightly different approach. Check out my article on inner border-radius.
Demo
Complete examples with code available on CodePen:
See the Pen Untitled by Tippingpoint Dev (@tippingpointdev) on CodePen.
Let’s start
You can see, we centered our Text element. right ? So, now style out text.
.text font-size: 150px; color: #eee; text-transform: capitalize; >
output
.text /*previous styles*/ background: linear-gradient(-45deg, #eeaa52, #e73c6f, #2394d5, #2af3b7); background-size: 200% 200%; >
output
But, we don’t want background color, right ? so for that use this property.
.text /*previous styles*/ -webkit-background-clip: text; >
What is this property for, this will only show background color within text. Means like this.
But this will only work if, text color is set to transparent. But in our case. Our text color is not transparent, because of that we’ll not be able to see any gradient color. I hope it makes sense. Now the last step, use -webkit-text-stroke property.
.text /*previous styles*/ -webkit-text-stroke: 8px transparent; >
here you can give any stroke color after 8px (stroke width) but by giving transparent, you are making space within the text, so our background gradient should be visible.
output
So, it’s done. I hope you understood each and everything. If you have doubt or I missed some point let me know in the comments.
Articles you may found Useful
If you like, you can subscribe my youtube channel, and follow me on instagram. I create awesome web contents. [Subscribe], [Instagram]
Градиентные границы в CSS
Доброго времени суток уважаемые хабровчане. Представляю вашему вниманию перевод статьи Криса Коера.
Допустим, вам нужна градиентная граница вокруг определенного элемента. И вы, такой, думаете:
- Для этого не существует простого и очевидного CSS API.
- Я просто сделаю элемент-обертку с линейно-градиентным фоном, а затем внутренний элемент заблокирует большую часть этого фона, за исключением тонкой линии заполнения вокруг него.
Выглядеть это будет как-то так:
Lorem ipsum dolor sit amet consectetur adipisicing elit. Vero pariatur corporis quaerat voluptatum eos tempora temporibus nisi voluptates sed, exercitationem sequi dolore culpa incidunt accusamus, quasi unde reprehenderit ea molestias.
body < height: 100vh; margin: 0; display: grid; place-items: center; background: #222; >.module-border-wrap < max-width: 250px; padding: 1rem; position: relative; background: linear-gradient(to right, red, purple); padding: 3px; >.module
Если вам не нравится идея оберточного элемента, вы можете использовать псевдоэлемент, до тех пор, пока отрицательное значение z-индекса в порядке (этого не произошло бы, если бы было много вложений родительских элементов с их собственными фонами).
Вот пример Стивена Шоу, закрепляющий border-radius :
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent bibendum, lorem vel tincidunt imperdiet, nibh elit laoreet felis, a bibendum nisl tortor non orci. Donec pretium fermentum felis, quis aliquet est rutrum ut. Integer quis massa ut lacus viverra pharetra in eu lacus. Aliquam tempus odio adipiscing diam pellentesque rhoncus. Curabitur a bibendum est.
Но не забывайте полностью о border-image , возможно, самом бестолковом свойстве CSS всех времен. Вы можете использовать его, чтобы получить градиентные границы даже на отдельных сторонах:
Lorem ipsum dolor sit amet consectetur adipisicing elit. Vero pariatur corporis quaerat voluptatum eos tempora temporibus nisi voluptates sed, exercitationem sequi dolore culpa incidunt accusamus, quasi unde reprehenderit ea molestias.
Использование как border-image , так и border-image-slice , вероятно, является самым простым синтаксисом для создания градиентной границы, но, к сожалению, это просто несовместимо с border-radius .
button < background: none; text-decoration: inherit; font-family: system-ui; font-size: 1rem; padding: 1rem 2rem; >.border-gradient < border-image-slice: 1; border-width: 2px; >.border-gradient-purple < border-image: linear-gradient(to left, #743ad5, #d53a9d); >.border-gradient-green < border-image: linear-gradient(to left, #00C853, #B2FF59); >body < height: 100vh; margin: 0; display: flex; justify-content: center; align-items: center; >div < width: 100%; text-align: center; >> div > div < width: 100%; padding: 1rem; >> .on-dark < background: #222; button < color: white; >>
Как задать градиент для border в CSS?
Рассмотрим как задать в CSS border gradient, это позволит вам создать на своём сайте красивый эффект градиентной рамки. В одной из предыдущих статей я подробно рассматривала как задать градиент в качестве фона.
Так вот, CSS 3 позволяет нам это сделать не только для фона, но и для рамки.
Навигация по статье:
Линейный градиент
Для примера рассмотрим такой блок:
Чтобы задать ему размеры, отступы и так далее я допишу следующие CSS свойства:
Теперь нам нужно задать толщину рамки и её тип:
Для задания градиента допишем свойство border-image в css файле:
Здесь мы в скобках задаём значения цветов, которые будут идти сверху вниз.
Чтобы наше CSS свойство работало во всех браузерах допишем кроссбраузерные префиксы:
-moz-border-image: -moz-linear-gradient(#0B0E7F , #0B95DD);
-webkit-border-image: -webkit-linear-gradient(#0B0E7F , #0B95DD);
И последнее зададим CSS свойство:
Чтобы заданный градиент сместился или растянулся по всей границе.
В итоге весь CSS код задания border gradient будет выглядеть так:
Вот результат работы кода:
Особенности border gradient в CSS
- 1 В скобках мы можем задать не обязательно 2 цвета, их может быть больше. Для этого просто указываем значения цветов через запятую:
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 слева направо: