- Цвет текста (color) в HTML
- Цвет в формате RGB
- Цвет в формате HEX
- Другие способы записи цвета?
- Change the Color of One Word in a String of Text in HTML
- Change the Color of One Word in a String of Text in HTML
- RGB Colors
- RGBA Colors
- HEX Colors
- HSL Colors
- HSLA Colors
- Change the Color of One Word in a String of Text in HTML Using Internal CSS
- Change the Color of One Word in a String of Text in HTML Using JavaScript
- HTML Code for Color Text
- Methods of Coding Color Text with HTML
- 1. Color HTML Text with Hex Color Codes
Цвет текста (color) в HTML
Одним из основных и наиболее часто используемых CSS свойств является цвет текста «color». Это свойство может принимать значения цвета, выраженные в разных единицах измерения. К примеру, в значении CSS свойства «color» напишем красный цвет (red) текстом:
Но очевидно, что если писать название цвета текстом, то нельзя выбрать оттенки. Поэтому существует ещё два других варианта выбора цветов. Рассмотрим их далее.
Цвет в формате RGB
В палитре RGB основными цветами являются красный, зелёный и синий. При смешении этих цветов получаются все остальные. Максимальное и минимальное значение каждого цвета может быть от 0 до 255. При смешивании трёх цветов со значениями из этого диапазона можно получить более 16 миллионов цветов (256 * 256 * 256 = 16 777 216). Этого вполне достаточно, чтобы человеческий глаз не замечал резкого перехода между цветами.
Приведём пример, как задать цвет через RGB в CSS. Сначала попробуем сделать текст красного цвета:
Как можно понять из записи, в скобках у rgb(. ) ставится уровень красного, зелёного и синего цвета, которым будет написан текст. Цвета ставятся в этой последовательности через запятую. Получается такой результат:
В палитре RGB чёрный цвет — это значение rgb(0, 0, 0), а белый цвет — это rgb(255, 255, 255). Теперь подмешаем к красному цвету зелёный в немного меньшем количестве. К примеру 150 единиц.
При смешении красного и зелёного получается жёлтый. Но так как пропорция неравная, поэтому жёлтый получился с оттенком оранжевого:
Таким образом можно получить любой цвет. Очевидно, что руками перебирать цвета довольно сложно, поэтому лучше использовать встроенные в браузер функции разработчика. В них можно не подбирать цифры наугад, а кликнуть на нужный цвет, что упрощает выбор. Но для практики попробуем сделать это.
Об инструментах разработчика сайтов читайте подробнее в статье «Средства разработки CSS». Там вы узнаете, как изменять CSS свойства на странице без её перезагрузки, как работать с консолью, как изменять значения cookie.
Цвет в формате HEX
Запись цвета в виде rgb(255, 150, 0) является довольно громоздкой. Но существует возможность записи цвета через шестнадцатеричное значение. Если в rgb указываются цвета в десятеричной системе счисления от 0 до 255, то в шестнадцатеричной системе эти числа будут соответствовать 0 и FF. А если записывать все три числа в скобках (255, 150, 0) в одну строку без запятых через эту систему, то получится FF9600 (FF = 250, 96 = 150, 0 = 00).
Запись цвета в формате HEX компактнее. Но её можно упростить ещё сильнее. Если первые три символа в этом формате идентичны второй тройке символов, то вторую стройку можно не писать. К примеру, если есть цвет «#F96F96», то можно записать цвет как «#F96».
Другие способы записи цвета?
Существуют и другие способы записи цвета, которые имеют свои преимущества и недостатки. К примеру, RGBA у которого в отличии от RGB есть ещё и четвёртое число, которое означает прозрачность. Но чаще всего используются записи значений цвета через HEX и RGB( . ).
Change the Color of One Word in a String of Text in HTML
- Change the Color of One Word in a String of Text in HTML
- Change the Color of One Word in a String of Text in HTML Using Internal CSS
- Change the Color of One Word in a String of Text in HTML Using JavaScript
The main topic of this article is utilizing CSS to highlight or change the color of any particular word in a text. We’ll go over several techniques for implementing this feature.
We will learn to color a text using internal and inline CSS. Later, we’ll look at how to use JavaScript to implement the same functionality.
Change the Color of One Word in a String of Text in HTML
We commonly see on websites that a single word in a text has a different color than the others; of course, it captures the users’ attention. Let’s discuss how we can do the same on our web pages.
In the earlier versions of HTML, we had a tag that can be used to implement this feature like this:
But the tag is removed in HTML5 and is no longer supported. So, we will learn about an HTML tag to help us do the task.
The element is an inline container to mark up a section of a text or a section of a page. The id or class attribute of the tag allows simple styling with CSS and modifications with JavaScript.
The tag also allows us to apply inline styling, similar to the div element. However, is an inline element, whereas div is a block-level element.
Check the example below to understand this.
html> body> p>Hello, I am span style="color: red">Redspan> p> body> html>
CSS’s color property gives the text a specific color. There are many ways to specify the required color; in the above example, we select the color by its name.
HTML can recognize 16 color names which are black, white, grey, silver, maroon, red, purple, fuchsia, green, lime, olive, yellow, navy, blue, teal, and aqua. New browsers can recognize 140 CSS color names.
You can check all the HTML-recognized color names from here. As we mentioned, many other ways to specify the required color exist.
Let’s have a look at different methods.
RGB Colors
RGB stands for red, green, blue. It uses an additive color scheme in which the three primary colors, Red, Green, and Blue, are combined to create each color.
The red, green, and blue parameters each have a value between 0 and 255 that describes the color’s intensity. This indicates that there are 256 x 256 x 256 = 16,777,216 distinct colors.
For instance, rgb(255, 0, 0) is rendered red because the color red is set to its greatest value, 255, while the other two colors, green and blue, are set to 0. Set all color parameters to zero like this rgb(0,0,0) to display black.
You can see the RGB value of different colors from here.
html> body> p>Hello, I am span style="color: rgb(241, 196, 15 )">Yellowspan> p> body> html>
RGBA Colors
RGBA colors are an extension of RGB colors, including an Alpha channel that determines a color’s opacity. The syntax for an RGBA color value is:
rgba (red, green, blue, alpha)
The value of the alpha parameter ranges from 0.0 (complete transparency) to 1.0 (full visibility). You can also use this property for the background colors, as sometimes we need different background colors with various opacity.
HEX Colors
Hex colors use hexadecimal values to represent colors from different color models. Hexadecimal colors are represented by the #RRGGBB , where RR stands for red, GG for green, and BB for blue.
The hexadecimal integers that specify the color’s intensity can range from 00 to FF ; an easy example is #0000FF . Because the blue component is at its highest value of FF while the red and green parts are at their lowest value of 00 , the color is entirely blue.
You can see the hex value of different colors from here.
html> body> p>Hello, I am span style="color: #0000FF">Bluespan> p> body> html>
HSL Colors
- Hue: The hue ranges from 0 to 360 degrees on the color wheel. Red is 0; yellow is 60; green is 120; blue is 240, etc.
- Saturation: This quantity is measured as a percentage, with 100% denoting fully saturated (i.e., no shades of grey), 50% denoting 50% grey but with still-visible color, and 0% indicating entirely unsaturated (i.e., completely grey and color invisible).
- Lightness: This is also a percentage: 0% is black, and 100% is white. The amount of light we wish to give a color is expressed as a percentage, with 0% being black (where there is no light), 50% representing neither dark nor light, and 100% representing white (complete lightness).
The syntax for HSL color values is:
hsl(hue, saturation, lightness)
You can see the HSL value of different colors from here.
html> body> p>Hello, I am span style="color: hsl(23, 97%, 50% )">Orangespan> p> body> html>
HSLA Colors
HSLA colors are an extension of HSL with an Alpha channel specifying a color’s opacity. An HSLA color value is determined with:
hsla(hue, saturation, lightness, alpha)
The value of the alpha parameter is a number having a range strictly between 0.0, which means fully transparent, and 1.0, which means not transparent.
Change the Color of One Word in a String of Text in HTML Using Internal CSS
We have seen in detail all the methods of giving color in CSS. We have been using inline CSS for everything up until this point.
However, inline CSS is not a suggested method because it is only tied to the element. We must rewrite much if we want the same functionality on different page regions.
So let’s color our text using Internal CSS, defined in the HTML tag inside a tag.
html> head> title>CSS Color Propertytitle> style> #rgb color:rgb(255,0,0); > #rgba color:rgba(255,0,0,0.5); > #hex color:#EE82EE; > #hsl color:hsl(0,50%,50%); > #hsla color:hsla(0,50%,50%,0.5); > #built color:green; > style> head> body> h1> Hello this is span id="built">Built-in colorspan> format. h1> h1> Hello this is span id="rgb">RGBspan> format. h1> h1> Hello this is span id="rgba">RGBAspan> format. h1> h1> Hello this is span id="hex">Hexadecimalspan> format. h1> h1> Hello this is span id="hsl">HSLspan> format. h1> h1> Hello this is span id="hsla">HSLAspan> format. h1> body> html>
Change the Color of One Word in a String of Text in HTML Using JavaScript
We can change the color of a specific word in a sentence using JavaScript. We need to give an ID to our tag and then get that element from JavaScript using document.getElementById(ID-name) and call the style property on it. Here’s how.
html> body onload="myFunction()"> p>Hello, I am span id="color-text">Magenta.span>p> script> function myFunction() document.getElementById("color-text").style.color = "magenta"; > script> body> html>
HTML Code for Color Text
HTML color codes are in a two digit hexadecimal format for red, blue, and green (#RRBBGG). Hexadecimal color codes go from 00 to DD. For example, #FF0000 would be red and #40E0D0 would be turquoise. Hexadecimal color codes are used in HTML for everything from text to backgrounds.
Coding a website in HTML, or HyperText Markup Language, is one of the most fundamental skills every coder must master. This markup language is how we organize, arrange, and format text and documents for use on websites. In this article, we’ll take a close look at HTML code for color text, an important design element for any website. Later, you can take what you’ve learned in this article and experiment in an HTML editor.
By continuing you agree to our Terms of Service and Privacy Policy, and you consent to receive offers and opportunities from Career Karma by telephone, text message, and email.
By continuing you agree to our Terms of Service and Privacy Policy, and you consent to receive offers and opportunities from Career Karma by telephone, text message, and email.
Methods of Coding Color Text with HTML
There are actually 4 different methods for coding text color with HTML. Let’s go over the 4 methods and take a look at some examples of each.
1. Color HTML Text with Hex Color Codes
The most common method of changing the color of the text is by using hexadecimal color codes, also known as Hex color codes. These codes are comprised of combinations of the integers 0, 1, 2, 3, 4, 5, 6, 7, 8, and 9; and the letters A, B, C, D, E, and F. So, a hex color code might be something like #FF0000 or #33DDFF.
Each hex color code corresponds to a specific color. For instance, our two examples above correspond to the following colors:
To find the hex color code you wish to use for your HTML text, you can use a site like HTML Color Codes, which offers interactive color charts and sliding scales. You can also use an eyedropper tool to match the hex color code of an element on your screen with a browser extension like ColorZilla.
Once you know your hex color code, adding a style attribute to change the color of your HTML text is simple. Just use the following code:
That code should produce the following colored text: