Градиентный текст

Градиентный текст

Для создания эффектных текстовых заголовков можно использовать градиент, который будет отображаться исключительно внутри букв. Ниже рассмотрим два способа добавления градиента к тексту, а также их плюсы и минусы.

Использование mix-blend-mode

Свойство mix-blend-mode определяет режим наложения цвета текста на фоновый цвет. Подобные режимы наложения можно увидеть в графических редакторах вроде Photoshop, соответственно, идея наложения и названия режимов позаимствованы оттуда.

Перед применением этого метода текст надо обернуть в какой-нибудь элемент (

, , , и др.) и установить для него родителя. Мы сделаем такую структуру: в качестве родителя; для текста.

Теперь для устанавливаем желаемый градиент через свойство background , а для ставим белый цвет фона и свойство mix-blend-mode со значением screen (пример 1).

Пример 1. Свойство mix-blend-mode

       

Градиентный текст

Результат данного примера показан на рис. 1.

Градиентный текст

Минусы

  • Метод годится только для белого фона веб-страницы, в остальных случаях градиент будет виден не только на тексте.
  • К тексту добавляется дополнительный родительский элемент.
  • Не поддерживается в браузерах IE и Edge. Однако в связи с переходом Edge на движок Chromium скоро начнёт поддерживать.

Плюсы

  • Градиентом легко управлять через стили.
  • Вместо градиента можно подставить изображение, заменив linear-gradient на значение url(image/bg.png) .

Использование -webkit-background-clip

Нестандартное свойство -webkit-background-clip со значением text позволяет установить цвет фона, в том числе градиент или картинку, только для текста. Градиент теперь применяем непосредственно к текстовому элементу ( в нашем случае) и включаем свойство -webkit-background-clip , а также -webkit-text-fill-color со значением transparent .

-webkit-text-fill-color нужен для того, чтобы убрать исходный цвет у самого текста, без этого свойства метод работать не будет (пример 2).

Пример 2. Свойство -webkit-background-clip

       

Градиентный текст

Результат данного примера показан на рис. 2.

Градиентный текст

Минусы

  • Мы используем нестандартные свойства, работу которых никто не гарантирует в будущем.
  • Не поддерживается браузером IE.

Плюсы

  • Градиентом легко управлять через стили.
  • Вместо градиента можно подставить изображение, заменив linear-gradient на значение url(image/bg.png) .
  • Поддерживается браузером Edge.
  • Метод годится для любого фона веб-страницы.
  • Не используются дополнительные элементы.

Таким образом, для фона веб-страницы, отличного от белого, подходит исключительно второй метод. Если же у вас белый цвет фона, то лучше использовать первый метод, поскольку в нём применяются стандартные свойства, которые будут поддерживаться браузерами и в дальнейшем.

Не выкладывайте свой код напрямую в комментариях, он отображается некорректно. Воспользуйтесь сервисом cssdeck.com или jsfiddle.net, сохраните код и в комментариях дайте на него ссылку. Так и результат сразу увидят.

Популярные материалы

  • Самоучитель HTML4
  • Самоучитель CSS
  • Как добавить картинку на веб-страницу?
  • Спецсимволы
  • Структура HTML-кода
  • Введение в HTML
  • Способы добавления стилей на страницу
  • Выравнивание текста
  • Якоря
  • Как добавить иконку сайта в адресную строку браузера?
  • Позиционирование элементов
  • Ссылки

Источник

How to Create Text Gradient in CSS?

Javascript Course - Mastering the Fundamentals

In this article, we are going to learn about text gradient CSS, so before getting started with the topic, let us get a short overview of what is text gradient in CSS.

Text gradients in CSS: A text gradient in CSS is a type of linear gradient for text styling in which the text is filled with colour. The text is coloured with a continuation from the start point to the endpoint. So, this type of transition in colour, from one to another colour, is done with help of the text gradient.

introduction to CSS Text Gradient

So let us now begin with the main agenda of our article, text gradient CSS.

Pre-requisites

Before learning about the text gradient in CSS, we must have a good understanding of the gradients and linear gradients in CSS. So, let us discuss them in detail too.

Gradients: A gradient in CSS is a continuation of colours with a starting and ending point, the gradual transition of colours from one colour (like red) to another colour (like blue), is a linear gradient. The perfect example of the linear gradient will be a sunset, we can observe how there is a transition of colours of the sunset from one colour to another beautifully and seamlessly.

When we are using these gradients in CSS for designing the text of any website or app we call it text gradient CSS. The text gradient is similar to a gradient, but just in the text gradient case, instead of filling a background, we use these gradient effects for text. However, we should never use text gradients in CSS for longer texts. Instead, we should use them to make headings or specific words more eye-catching. If you want to learn more about the gradient you can refer to Gradient.

Why Text Gradients Matter:

Now, there are several reasons why coders and web developers use gradient text most of the time gradients are one of the latest crazes in website design for a few reasons:

  • The text gradient CSS is very easy to implement, that is, once you know what effects you can use to make the text look very attractive, it will be a cake work for you.
  • The text gradients CSS have wonderful visual effects (especially, in the case of dark-theme websites or apps).
  • It is a very useful tool for our website if we know how to create a text gradient effect with our text (whether muted text gradients or bright and highly colourful).

Syntax

The most important part of your text gradient CSS is the actual CSS syntax itself. Check out the basic form of the CSS syntax.

Explanation:

We are using the linear gradient method to create a gradient background and then we are using the WebKit properties to overlay that background with our text.

Let us understand this syntax with the example below.

Explanation:

Let us understand the above example code :

  • In the above code, there is a heading tag ( ) inside the body tag ( ), to which we are going to add the text gradient effect.
  • In the head block, we have applied the Internal or Embedded CSS.
  • In which we have done the styling of the body tag , which includes basic background styling.
  • Then we have done some basic styling for the heading tag ( ), which includes font-size .
  • Then we applied the linear-gradient effect to the heading tag ( ), with the colour rgb(188, 12, 241) to rgb(212, 4, 4)`. You can use any colour of your choice.
  • Then we applied the WebKit properties, the first property -webkit-background-clip: text; will turn the whole gradient-background transparent, and the second property -webkit-text-fill-color: transparent; will fill the heading tag ( ) text with the gradient background.

What You Will Need to Know

To construct your text gradient syntax, you must first break down the basics. Let us learn about some of the keywords that would help in building the basics of what you will need to create your text gradient :

Font Size

This one is self-explanatory. Before setting up the other gradient properties, you will need to set up the font size of the text, that is, how large you would like your text font to be. The font size unit in CSS is based on EMS, pixels, points, and percentages. You might required to look up the conversions, but usually you can expect 1em = 12pt = 16px = 100% .

Let us look at an example for font size, for more clarity and better understanding.

Direction

The text gradient CSS is not much different from the linear gradient, especially in the case of direction. We define the angle of a linear gradient in the code in form of a keyword or number and unit. There are varieties of keywords like to the top, to bottom, to left, and to right which we can use with the linear gradient to decide the direction of the line from the starting point. We can combine these directional keywords, for instance — to the top right or to the bottom left (usually to create a diagonal line). The number and unit pairings can also be used to decide the angle and direction of the line.

Let us look at an example for direction, for more clarity and better understanding.

Colors and Color Stops

We will need at least two colours for the gradient to transition between to create the simplest sort of text gradients in CSS. In essence, the colour stops refer to the code point along the text gradient where each colour should end. These hues can have any basis, including name, HEX , RGB , or HSL . As a result, there are numerous alternatives for how your gradient can be shown.

Let us look at an example for Colors and Color Stops, for more clarity and better understanding.

How to Create Text Gradient in CSS?

Let us now see how we can create text gradients in CSS step by step.

HTML Code

In the following section, the text used for the text gradient CSS demonstration is wrapped inside the heading tag h1 tag. Let us look at the code for it.

CSS Code

For CSS code, we need to follow the given steps below :

  • Step 1: Inside the CSS code we will first apply some basic background to the body and align the text to the centre of the page.

Output:

  • Step 2: Then we will do some basic styling of the heading tag ( ), like adjusting the font size and family, etc.

  • Step 3: Then we will apply the linear gradient property on the heading tag text with any colours of your choice.

Output:

  • Step 4: Then with the help of WebKit properties, we will make the entire gradient background transparent, and then we will fill the text with a gradient background.

Complete Code: Let us look at the complete code by combining both the above sections of code.

Example

Now let us look at an example of text gradients CSS, for better understanding.

Explanation:

Let us understand the above code in detail:

  • Firstly, inside the HTML code, there is a heading tag ( ) with the class name as rainbow-text , inside the body tag ( ), to which we are going to add the text gradient effect.
  • Then we are applying the external CSS, to this HTML code.
  • Inside the CSS code, at first we have done the general styling of the page, such as setting the background colour, font size, etc.
  • Then we styled the heading tag of the HTML code, by calling its class name rainbow-text .
  • In which we have styled the text with the conic gradient, with double percentage to avoid blur. The conic gradient is also similar to the linear gradient, just in the case of the conic gradient the colour transitions rotated around a centre point.
  • Then. we have set the background size and repeat properties.
  • Then with the help of WebKit properties, we will make the entire gradient background transparent, and then we will fill the text with a gradient background.
  • Then we have also added animation to the text when loading the element. This animation property animates the text on page load and when hovering out.
  • We have also added animation on hover.
  • Then we have also added the effect of moving the background and making it larger. The animation showed when hovering over the text.
  • Also, moving the background and making it smaller. The animation showed when entering the page and after the hover animation.

Conclusion

In this article, we learned about text gradient CSS. Let us recap the points we discussed throughout the article:

  • A text gradient in CSS is a type of linear gradient for text styling in which the text is filled with colour.
  • Before learning about the text gradient in CSS, we must have a good understanding of the gradients and linear gradients in CSS.
  • A gradient in CSS is a continuation of colours with a starting and ending point, the gradual transition of colours from one colour (like red) to another colour (like blue), is a linear gradient.
  • The text gradient is similar to gradient, but just in the text gradient case, instead of filling a background, we use these gradient effects for text.
  • The text gradient CSS is very easy to implement.
  • We have seen the syntax of text gradient CSS.
  • To construct your text gradient syntax, you must have a good knowledge of the Font Size, Direction, Colors, and Color Stops.
  • Then we have seen how we can create text gradient step by step. Also, we have seen an example of using conical gradient for text styling, which includes animation while hovering and page reloading.

Источник

Читайте также:  Язык разметки html виды тегов
Оцените статью