Здравствуйте, дороге друзья!
При оформлении текста на сайте нам часто приходится изменять цвет текста, размер, жирность, начертание и так далее. В этой статье вы узнаете как в HTML изменить цвет текста не прибегая к помощи дополнительных плагинов, модулей и библиотек.
Навигация по статье:
- Изменения цвета текста средствами HTML
- Как изменить цвет текста в HTML с использованием CSS?
- Изменяем цвет в HTML коде при помощи атрибута style
- Что делать если внесённые изменения не меняются?
Если ваш сайт сделан на одной из CMS, то для изменения цвета текста вы можете использовать встроенный функционал визуального редактора, однако такая функция там не всегда есть, а ставить ради этого дополнительный модуль или плагин не всегда есть смысл.
Плюс бывают ситуации когда вам нужно изменить цвет текста в виджете или слайдере или ещё где то, где визуальный редактор не поддерживается.
К счастью в HTML есть специальный тег с атрибутом color, в котором можно указать нужный цвет текста.
<font color=«red»>Красный текст</font> |
Значение цвета можно задавать несколькими способами:
- При помощи кодового названия (Например: red, black, blue)
- В шестнадцатиричном формате (Например: #000000, #ccc)
- В формате rgba (Например: rgba(0,0,0,0.5))
Если вы ещё не знаете как определить значение цвета на сайте, то вам сюда
Таким образом вы можете изменить цвет у целого абзаца, слова или одной буквы, обернув то что вам нужно в тег <font>
Как изменить цвет текста в HTML с использованием CSS?
Для изменения цвета текста для определённого абзаца или слова можно присвоить ему класс, а затем в CSS файле задать для этого класса свойство color.
Выглядеть это будет так:
HTML
<p class=”color—text”>Пример текста</div> |
CSS
.color—text { color:#555555; } |
Вместо color-text вы можете указать свой класс.
Если вам нужно изменить цвет текста для элемента на сайте у которого уже есть класс или идентификатор, то можно вычислить его название и указать в CSS.
Если вы не хотите лезть в CSS файл чтобы внести изменения, то можно дописать CSS стили прямо в HTML коде станицы, воспользовавшись тегом <style>.
Для этого:
- 1.Находи вверху HTML страницы тег </head>. Если ваш сайт работает на CMS, то этот фрагмент кода находится в одном из файлов шаблона. Например: header.php, head.php или что-то наподобие этого в зависимости от CMS.
- 2.Перед строкой </head> добавляем теги <style>…</style>.
- 3.Внутри этих тегов задаём те CSS свойства, которые нам нужны. В данном случае color:
<style>
.color-text {
color:#555555;
}
</style>
Этот способ подходит если вам нужно изменить цвет сразу для нескольких элементов на сайте.
Если же такой элемент один, то можно задать или изменить цвет текста прямо в HTML коде.
Изменяем цвет в HTML коде при помощи атрибута style
Для этого добавляем к тегу для которого нам нужно изменить цвет текста атрибут style.
<p style=”color:red;”>Пример</p> |
Здесь же при необходимости через ; вы можете задать и другие CSS свойства, например, размер шрифта, жирность и так далее.
<p style=”color:red; font—size:20px; font—weight:bolder;”>Пример</p> |
Лично я обычно использую вариант с заданием стилей в CSS файле, но если вам нужно изменить цвет текста для какого то одного-двух элементов, то не обязательно присваивать им класс и потом открывать CSS файл и там дописывать слили. Проще это сделать прямо в HTML при помощи тега <font> или артибута style.
Так же вы должны знать, что есть такое понятие как приоритет стилей. Так вот когда вы задаёте цвет текста или другие стили в html при помощи атрибута style, то у этих стилей приоритет будет выше чем если вы их зададите в CSS файле (при условии что там не использовалось правило !important)
Чтобы изменить цвет текста отдельного слова, фразы или буквы мы можем обернуть их в тег span и задать ему нужный цвет.
Например:
<p>Пример <span style=”color:#2F73B6;”> текста</span></p> |
В итог получится вот так:
Пример текста
Что делать если внесённые изменения не меняются?
Казалось бы, изменение цвета – одна из простейших операций при оформлении текста, ну что здесь может пойти не так?
Однако и здесь есть свои нюансы, которые нужно учитывать:
- 1.Приоритет стилей, о котором я писала выше. Если задавать цвет текста прямо в HTML то приоритет будет выше. Если вы задали его при помощи атрибута style, а он всё равно не изменилcя, то попробуйте добавить к нему правило !important;
<p style=”color:#fff!important;”>…</p>
- 2.Особенности тегов. Если вы зададите цвет текста для абзаца внутри которого есть ссылка, то он изменится для всего абзаца кроме ссылки. Чтобы изменился цвет ссылки нужно задавать его именно для тега ссылки.
Аналогично если вы зададите цвет текста для блока, внутри которого находится список, то для элементов этого списка он может не примениться и нужно будет отдельно задавать его именно для тегов списка.
- 3.Кеширование. Часто современные браузеры кешируют стили сайта и даже после внесения изменений в код они ещё какое то время отображают старую версию стилей. Для решения проблемы можно обновлять страницу при помощи сочетания клавиш CTRL+F5.
Так же у вас на сайте может стоять плагин для кеширования, из-за которого вы так же можете не видеть внесённых изменений на сайте.
Вот, в общем то и всё что касается изменения цвета в HTML. Как видите, ничего сложного! Если у вас возникнут какие то вопросы – пишите их в комментариях.
Успехов вам и вашим проектам!
С уважением Юлия Гусарь
Загрузить PDF
Загрузить PDF
В HTML цвет текста меняется с помощью тега <font>, но этот метод больше не поддерживается в HTML5. Вместо указанного тега нужно пользоваться CSS, чтобы задать цвет текста различных элементов страницы. Использование CSS гарантирует, что веб-страница будет совместима с любым браузером.
-
1
Откройте файл HTML. Лучший способ изменить цвет текста — это воспользоваться CSS. Старый тег <font> больше не поддерживается в HTML5. Поэтому воспользуйтесь CSS, чтобы определить стиль элементов страницы.
- Этот метод также применим к внешним таблицам стилей (отдельным файлам CSS). Приведенные ниже примеры предназначены для файла HTML с внутренней таблицей стилей.
-
2
Размеcтите курсор внутри тега <head>. Стили определяются внутри этого тега, если используется внутренняя таблица стилей.
-
3
Введите <style>, чтобы создать внутреннюю таблицу стилей. Когда тег <style> находится внутри тега <head>, таблица стилей, которая находится внутри тега <style>, будет применена к любым элементам страницы. Таким образом, начало HTML-файла должно выглядеть следующим образом:[1]
<!DOCTYPE html> <html> <head> <style> </style> </head>
-
4
Введите элемент, цвет текста которого нужно изменить. Используйте раздел <style>, чтобы определить внешний вид элементов страницы. Например, чтобы изменить стиль всего текста на странице, введите следующее:
<!DOCTYPE html> <html> <head> <style> body { } </style> </head>
-
5
В селекторе элемента введите атрибут color:. Этот атрибут определяет цвет текста выбранного элемента. В нашем примере этот атрибут изменит цвет основного текста, который является элементом, включающим весь текст на странице:
<!DOCTYPE html> <html> <head> <style> body { color: } </style> </head>
-
6
Введите цвет текста. Это можно сделать тремя способами: ввести имя, ввести шестнадцатеричное значение или ввести значение RGB. Например, чтобы сделать текст синим, введите blue, rgb(0, 0, 255) или #0000FF.
<!DOCTYPE html> <html> <head> <style> body { color: red; } </style> </head>
-
7
Добавьте другие селекторы, чтобы изменить цвет различных элементов. Можно использовать различные селекторы, чтобы менять цвет текста разных элементов страницы:
<!DOCTYPE html> <html> <head> <style> body { color: red; } h1 { color: #00FF00; } p { color: rgb(0,0,255) } </style> </head> <body> <h1>Этот заголовок будет зеленым.</h1> <p>Этот параграф будет синим.</p> Этот основной текст будет красным. </body> </html>
-
8
Укажите стилевой класс CSS вместо того, чтобы менять элемент. Можно указать стилевой класс, а затем применить его к любому элементу страницы, чтобы изменить стиль элемента. Например, класс .redtext окрасит текст элемента, к которому применен этот класс, в красный цвет:
<!DOCTYPE html> <html> <head> <style> .redtext { color: red; } </style> </head> <body> <h1 class="redtext"> Этот заголовок будет красным</h1> <p>Этот параграф будет стандартным.</p> <p class="redtext">Этот параграф будет красным</p> </body> </html>
Реклама
-
1
Откройте файл HTML. Можно воспользоваться атрибутами встроенного стиля, чтобы изменить стиль одного элемента страницы. Это может быть полезно, если нужно внести одно-два изменения в стиль, но не рекомендуется для широкомасштабного применения. Чтобы полностью изменить стиль, используйте предыдущий метод.[2]
-
2
Найдите элемент, который нужно изменить.
С помощью атрибутов встроенного стиля можно изменить цвет текста любого элемента страницы. Например, чтобы изменить цвет текста определенного заголовка, найдите его в файле:<!DOCTYPE html> <html> <body> <h1>Этот заголовок нужно изменить</h1> </body> </html>
-
3
К элементу добавьте атрибут стиля. Внутри открывающего тега изменяемого элемента введите style="":
<!DOCTYPE html> <html> <body> <h1 style="">Этот заголовок нужно изменить</h1> </body> </html>
-
4
Внутри "" введите color:. Например:
<!DOCTYPE html> <html> <body> <h1 style="color:">Этот заголовок нужно изменить </h1> </body> </html>
-
5
Введите цвет текста. Это можно сделать тремя способами: ввести имя, ввести шестнадцатеричное значение или ввести значение RGB. Например, чтобы сделать текст желтым, введите yellow;, rgb(255,255,0); или #FFFF00;:
<!DOCTYPE html> <html> <body> <h1 style="color:#FFFF00;">Этот заголовок стал желтым</h1> </body> </html>
Реклама
Советы
- Список поддерживаемых цветов и их шестнадцатеричные значения можно найти на сайте http://www.w3schools.com/colors/colors_names.asp
Реклама
Об этой статье
Эту страницу просматривали 242 817 раз.
Была ли эта статья полезной?
Цвет шрифта на сайте можно задать при помощи HTML-кода. Для этого существует тег font. По определению, тег font служит некой «обёрткой» или «контейнером» для текста, управляя свойствами которого можно изменять оформление текста.
Тег font применяется следующим образом:
<p>Конструктор сайтов <font>"Нубекс"</font></p>
Самый простой способ, как изменить цвет шрифта в HTML, это использовать атрибут color тега font:
Конструктор сайтов <font color="blue">"Нубекс"</font>
Здесь задается синий цвет для слова, обрамленного тегом font.
Но помимо параметра color, тег имеет и другие атрибуты.
Атрибуты тега FONT
Тег font имеет всего три атрибута:
- color – задает цвет текста;
- size – устанавливает размер текста;
- face – задает семейство шрифтов.
Параметр color может быть определен названием цвета (например, “red”, “blue”, “green”) или шестнадцатеричным кодом (например, #fa8e47).
Атрибут size может принимать значения от 1 до 7 (по умолчанию равен 3, что соответствует 13,5 пунктам для шрифта Times New Roman). Другой вариант задания атрибута – “+1” или “-1”. Это означает, что размер будет изменен относительно базового на 1 больше или меньше, соответственно.
Рассмотрим применение этих атрибутов на нашем примере:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Меняем цвет шрифта при помощи HTML</title>
</head>
<body>
<p>Конструктор сайтов <font size="6" color="#fa8e47" face="serif">"Нубекс"</font></p>
</body>
</html>
Мы применили тег font к одному слову, задали для него размер 6, оранжевый цвет и семейство шрифтов “Serif”.
Задание цвета текста при помощи CSS
Если вам нужно применить определенное форматирование (например, изменить цвет текста) к нескольким участкам текста, то более правильно будет воспользоваться CSS-кодом. Для этого существует атрибут color. Рассмотрим способ его применения на нашем примере:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Меняем цвет шрифта при помощи CSS</title>
<style>
.nubex {
color:#fa8e47;
font-size: 150%;
}
.constructor {
color: blue;
}
.saitov {
color: green;
font-size: 125%;
}
</style>
</head>
<body>
<p><span class="constructor">Конструктор</span> <span class="saitov">сайтов</span> <span class="nubex">"Нубекс"</span></p>
</body>
</html>
Здесь мы задали синий цвет для слова «Конструктор» (размер его, по умолчанию, 100% от базового), зеленый цвет и размер 125% для слова «сайтов», оранжевый цвет и размер 150% для слова «Нубекс».
Download Article
Easily change the color of text using CSS or HTML
Download Article
- Creating Text Styles
- Using Inline Styles
- Q&A
- Tips
|
|
|
Do you want to change the color of the text on a web page? In HTML5, you can use CSS to define what color the text will appear in various elements on your page. You can also use inline style attributes to change the color of individual text elements in your CSS file. Using CSS will ensure that your web page is compatible with every possible browser. You can also use external CSS files to create a standard font color for a specific style across your entire website. This wikiHow article teaches you how to change text color using HTML and CSS.
-
1
Open your HTML file. The best way to change the color of your text is by using CSS. The old HTML <font> attribute is no longer supported in HTML5. The preferred method is to use CSS to define the style of your elements. Go ahead and open or create a new HTML document.
- This method will also work with separate CSS files that are linked to your HTML document. The examples used in this article are for an HTML file using an internal stylesheet.
-
2
Place your cursor inside the head of your HTML file. When you are using an internal style sheet for a specific HTML file, it is usually placed within the head of the HTML file. The head is at the top of the sheet in between the opening <head> tag, and the closing </head> tag.
- If your HTML document does not have a head, go ahead and enter the opening and closing head tags at the top of your HTML file.
Advertisement
-
3
Type the opening and closing tags for the style sheet. All CSS elements that affect the style of the webpage go in between the opening and closing style tags within the head section of your HTML document. Type <style> in the «head» section to create the opening style tag. Then type </style> a couple of lines down to create the closing style tag. When you’re finished, the beginning of your HTML file should look something like this:[1]
<!DOCTYPE html> <html> <head> <style> </style> </head>
-
4
Type the element you want to change the text color for followed by the opening and closing brackets. Elements you can change include the text body (body), paragraph text («<p>»), as well as headers («<h1>», «<h2>», «<h3>», etc.). Then enter the opening bracket («{«) one space after. Then add the closing bracket («}») a few lines down. In this example, we will be changing the «body» text. The beginning of your HTML file should look something like the following:
<!DOCTYPE html> <html> <head> <style> body { } </style> </head>
-
5
Add the color attribute into the element section of the CSS. Type color: in between the opening and closing brackets of the text element you just created. The «color:» attribute will tell the page what text color to use for that element. So far, the head of your HTML file should look something like the following:
<!DOCTYPE html> <html> <head> <style> body { color: } </style> </head>
-
6
Type in a color for the text followed by a semi-colon («;»). There are three ways you can enter a color: the name, the hex value, or the RGB value. For example, for the color blue you could type blue; for the color name, rgb(0, 0, 255); for the RGB value, or #0000FF; for the hex value. Your HTML page should look something like the following:
<!DOCTYPE html> <html> <head> <style> body { color: red; } </style> </head>
-
7
Add other selectors to change the color of various elements. You can use different selectors to change the color of different text elements. If you want the header to be a different color than the paragraph text or body text, you will need to create a different selector for each element within the «<style>» section. In the following example, we change the color of the body text to red, the header text to green, and the paragraph text to blue:
<!DOCTYPE html> <html> <head> <style> body { color: red; } h1 { color: #00FF00; } p { color: rgb(0,0,255) } </style> </head> <body> <h1>This header will be green.</h1> <p>This paragraph will be blue.</p> This body text will be red. </body> </html>
-
8
Define a CSS class that changes text color. In CSS, you can define a class rather than using the existing elements. You can apply the class to any text element within your HTML document. To do so, type a period («.») followed by the name of the class you’d like to define. In the following example, we define a new class called «.redtext», which changes the color of the text to red. Then we apply it to the header at the top of the HTML document. Checkout the following example:
<!DOCTYPE html> <html> <head> <style> .redtext { color: red; } </style> </head> <body> <h1 class="redtext">This heading will be red</h1> <p>This paragraph will be normal.</p> <p class="redtext">This paragraph will be red</p> </body> </html>
Advertisement
-
1
Open your HTML file. You can use inline HTML style attributes to change the style of a single element on your page. This can be useful for one or two quick changes to the style but is not recommended for widespread use. It’s best to use CSS for comprehensive changes. Go ahead and open or create a new HTML document.[2]
-
2
Find the text element in the file that you want to change. You can use inline style attributes to change the text color of any of your text elements, including paragraph text («<p>»»), or your headline text («<h1>»).
<!DOCTYPE html> <html> <body> <h1>This is the header you want to change</h1> </body> </html>
-
3
Add the style attribute to the element. To do so, Type style="" inside the opening tag for the element you want to change. In the following example, we have added the style attribute to the header text:
<!DOCTYPE html> <html> <body> <h1 style="">This is the header you want to change</h1> </body> </html>
-
4
Type the color: attribute inside the quotation marks. Type «color» with a colon («:») within the quotation marks after the style attribute. So far, your HTML file should look something like the following:
<!DOCTYPE html> <html> <body> <h1 style="color:">This is the header you want to change</h1> </body> </html>
-
5
Type the color you want to change the text to followed by a semi-colon («;»). There are three ways you can express a color. You can type the name of the color, you can enter the RGB value, or you can enter the hex value. For example, to change the color to yellow, you could type yellow; for the color name, rgb(255,255,0); for the RGB value, or #FFFF00; to use the hex value. In the following example, we change the headline color to yellow using the hex value:
<!DOCTYPE html> <html> <body> <h1 style="color:#FFFF00;">This header is now yellow</h1> </body> </html>
Advertisement
Add New Question
-
Question
How would I type bold font in html?
<b></b> is the code for bold text, so you would put your text within that, e.g. <b> hello world </b>.
-
Question
How do I change background colors in HTML?
Use the bgcolor attribute with body tag.
-
Question
How do I change the color of the background?
You will create a similar tag as you did to change the font color. After putting everything in the body tag, you will put the {} brackets and on the inside, type «background-color:(insert desired color).» In code, it should look like this:
body {
color: black;
background-color:gold
}This code gives you black text and a gold background.
See more answers
Ask a Question
200 characters left
Include your email address to get a message when this question is answered.
Submit
Advertisement
-
You can see a list of supported color names and their hex values at http://www.w3schools.com/colors/colors_names.asp
Thanks for submitting a tip for review!
Advertisement
About This Article
Article SummaryX
1. Open the file in a text editor.
2. Find the element you want to change.
3. Type style=″color:#FFFF00;″ in the opening tag.
4. Replace ″#FFFF00″ with your desired color.
Did this summary help you?
Thanks to all authors for creating a page that has been read 1,980,696 times.
Is this article up to date?
Download Article
Easily change the color of text using CSS or HTML
Download Article
- Creating Text Styles
- Using Inline Styles
- Q&A
- Tips
|
|
|
Do you want to change the color of the text on a web page? In HTML5, you can use CSS to define what color the text will appear in various elements on your page. You can also use inline style attributes to change the color of individual text elements in your CSS file. Using CSS will ensure that your web page is compatible with every possible browser. You can also use external CSS files to create a standard font color for a specific style across your entire website. This wikiHow article teaches you how to change text color using HTML and CSS.
-
1
Open your HTML file. The best way to change the color of your text is by using CSS. The old HTML <font> attribute is no longer supported in HTML5. The preferred method is to use CSS to define the style of your elements. Go ahead and open or create a new HTML document.
- This method will also work with separate CSS files that are linked to your HTML document. The examples used in this article are for an HTML file using an internal stylesheet.
-
2
Place your cursor inside the head of your HTML file. When you are using an internal style sheet for a specific HTML file, it is usually placed within the head of the HTML file. The head is at the top of the sheet in between the opening <head> tag, and the closing </head> tag.
- If your HTML document does not have a head, go ahead and enter the opening and closing head tags at the top of your HTML file.
Advertisement
-
3
Type the opening and closing tags for the style sheet. All CSS elements that affect the style of the webpage go in between the opening and closing style tags within the head section of your HTML document. Type <style> in the «head» section to create the opening style tag. Then type </style> a couple of lines down to create the closing style tag. When you’re finished, the beginning of your HTML file should look something like this:[1]
<!DOCTYPE html> <html> <head> <style> </style> </head>
-
4
Type the element you want to change the text color for followed by the opening and closing brackets. Elements you can change include the text body (body), paragraph text («<p>»), as well as headers («<h1>», «<h2>», «<h3>», etc.). Then enter the opening bracket («{«) one space after. Then add the closing bracket («}») a few lines down. In this example, we will be changing the «body» text. The beginning of your HTML file should look something like the following:
<!DOCTYPE html> <html> <head> <style> body { } </style> </head>
-
5
Add the color attribute into the element section of the CSS. Type color: in between the opening and closing brackets of the text element you just created. The «color:» attribute will tell the page what text color to use for that element. So far, the head of your HTML file should look something like the following:
<!DOCTYPE html> <html> <head> <style> body { color: } </style> </head>
-
6
Type in a color for the text followed by a semi-colon («;»). There are three ways you can enter a color: the name, the hex value, or the RGB value. For example, for the color blue you could type blue; for the color name, rgb(0, 0, 255); for the RGB value, or #0000FF; for the hex value. Your HTML page should look something like the following:
<!DOCTYPE html> <html> <head> <style> body { color: red; } </style> </head>
-
7
Add other selectors to change the color of various elements. You can use different selectors to change the color of different text elements. If you want the header to be a different color than the paragraph text or body text, you will need to create a different selector for each element within the «<style>» section. In the following example, we change the color of the body text to red, the header text to green, and the paragraph text to blue:
<!DOCTYPE html> <html> <head> <style> body { color: red; } h1 { color: #00FF00; } p { color: rgb(0,0,255) } </style> </head> <body> <h1>This header will be green.</h1> <p>This paragraph will be blue.</p> This body text will be red. </body> </html>
-
8
Define a CSS class that changes text color. In CSS, you can define a class rather than using the existing elements. You can apply the class to any text element within your HTML document. To do so, type a period («.») followed by the name of the class you’d like to define. In the following example, we define a new class called «.redtext», which changes the color of the text to red. Then we apply it to the header at the top of the HTML document. Checkout the following example:
<!DOCTYPE html> <html> <head> <style> .redtext { color: red; } </style> </head> <body> <h1 class="redtext">This heading will be red</h1> <p>This paragraph will be normal.</p> <p class="redtext">This paragraph will be red</p> </body> </html>
Advertisement
-
1
Open your HTML file. You can use inline HTML style attributes to change the style of a single element on your page. This can be useful for one or two quick changes to the style but is not recommended for widespread use. It’s best to use CSS for comprehensive changes. Go ahead and open or create a new HTML document.[2]
-
2
Find the text element in the file that you want to change. You can use inline style attributes to change the text color of any of your text elements, including paragraph text («<p>»»), or your headline text («<h1>»).
<!DOCTYPE html> <html> <body> <h1>This is the header you want to change</h1> </body> </html>
-
3
Add the style attribute to the element. To do so, Type style="" inside the opening tag for the element you want to change. In the following example, we have added the style attribute to the header text:
<!DOCTYPE html> <html> <body> <h1 style="">This is the header you want to change</h1> </body> </html>
-
4
Type the color: attribute inside the quotation marks. Type «color» with a colon («:») within the quotation marks after the style attribute. So far, your HTML file should look something like the following:
<!DOCTYPE html> <html> <body> <h1 style="color:">This is the header you want to change</h1> </body> </html>
-
5
Type the color you want to change the text to followed by a semi-colon («;»). There are three ways you can express a color. You can type the name of the color, you can enter the RGB value, or you can enter the hex value. For example, to change the color to yellow, you could type yellow; for the color name, rgb(255,255,0); for the RGB value, or #FFFF00; to use the hex value. In the following example, we change the headline color to yellow using the hex value:
<!DOCTYPE html> <html> <body> <h1 style="color:#FFFF00;">This header is now yellow</h1> </body> </html>
Advertisement
Add New Question
-
Question
How would I type bold font in html?
<b></b> is the code for bold text, so you would put your text within that, e.g. <b> hello world </b>.
-
Question
How do I change background colors in HTML?
Use the bgcolor attribute with body tag.
-
Question
How do I change the color of the background?
You will create a similar tag as you did to change the font color. After putting everything in the body tag, you will put the {} brackets and on the inside, type «background-color:(insert desired color).» In code, it should look like this:
body {
color: black;
background-color:gold
}This code gives you black text and a gold background.
See more answers
Ask a Question
200 characters left
Include your email address to get a message when this question is answered.
Submit
Advertisement
-
You can see a list of supported color names and their hex values at http://www.w3schools.com/colors/colors_names.asp
Thanks for submitting a tip for review!
Advertisement
About This Article
Article SummaryX
1. Open the file in a text editor.
2. Find the element you want to change.
3. Type style=″color:#FFFF00;″ in the opening tag.
4. Replace ″#FFFF00″ with your desired color.
Did this summary help you?
Thanks to all authors for creating a page that has been read 1,980,696 times.
Is this article up to date?
Text plays a significant role on our web pages. This is because it helps users learn what the web page is all about and what they can do there.
When you add text to your web pages, this text defaults to a black color. But sometimes you will want to change the text color to be more personalized.
For example, suppose you have a darker color as the background of your website. In that case, you’ll want to make the text color a lighter, brighter color to improve your website’s readability and accessibility.
In this article, you will learn how to change the color of your text in HTML. We’ll look at various methods, and we’ll discuss which method is best.
How to Change Text Color Before HTML5
Before the introduction of HTML5, you’d use <font>
to add text to websites. This tag takes the color
attribute, which accepts the color as a name or hex code value:
<font color="#9900FF"> Welcome to freeCodeCamp. </font>
// Or
<font color="green"> Welcome to freeCodeCamp. </font>
This tag got depreciated when HTML5 was introduced. This makes sense because HTML is a markup language, not a styling language. When dealing with any type of styling, it is best to use CSS, which has the primary function of styling.
This means for you to add color to your web pages, you need to make use of CSS.
In case you are in a rush to see how you can change the color of your text, then here it is:
// Using inline CSS
<h1 style="color: value;"> Welcome to freeCodeCamp! </h1>
// Using internal/external CSS
selector {
color: value;
}
Suppose you are not in a rush. Let’s briefly dive right in.
You can use the CSS color property to change the text color. This property accepts color values like Hex codes, RGB, HSL, or color names.
For example, if you want to change the text color to sky blue, you can make use of the name skyblue
, the hex code #87CEEB
, the RGB decimal code rgb(135,206,235)
, or the HSL value hsl(197, 71%, 73%)
.
There are three ways you can change the color of your text with CSS. These are using inline, internal, or external styling.
How to Change Text Color in HTML With Inline CSS
Inline CSS allows you to apply styles directly to your HTML elements. This means you are putting CSS into an HTML tag directly.
You can use the style attribute, which holds all the styles you wish to apply to this tag.
<p style="...">Welcome to freeCodeCamp!</p>
You will use the CSS color property alongside your preferred color value:
// Color Name Value
<p style="color: skyblue">Welcome to freeCodeCamp!</p>
// Hex Value
<p style="color: #87CEEB">Welcome to freeCodeCamp!</p>
// RGB Value
<p style="color: rgb(135,206,235)">Welcome to freeCodeCamp!</p>
// HSL Value
<p style="color: hsl(197, 71%, 73%)">Welcome to freeCodeCamp!</p>
But inline styling isn’t the greatest option if your apps get bigger and more complex. So let’s look at what you can do instead.
How to Change Text Color in HTML With Internal or External CSS
Another preferred way to change the color of your text is to use either internal or external styling. These two are quite similar since both use a selector.
For internal styling, you do it within your HTML file’s <head>
tag. In the <head>
tag, you will add the <style>
tag and place all your CSS stylings there as seen below:
<!DOCTYPE html>
<html>
<head>
<style>
selector {
color: value;
}
</style>
</head>
// ...
</html>
While for external styling, all you have to do is add the CSS styling to your CSS file using the general syntax:
selector {
color: value;
}
The selector can either be your HTML tag or maybe a class
or an ID
. For example:
// HTML
<p> Welcome to freeCodeCamp! </p>
// CSS
p {
color: skyblue;
}
Or you could use a class
:
// HTML
<p class="my-paragraph" > Welcome to freeCodeCamp! </p>
// CSS
.my-paragraph {
color: skyblue;
}
Or you could use an id
:
// HTML
<p id="my-paragraph" > Welcome to freeCodeCamp! </p>
// CSS
#my-paragraph {
color: skyblue;
}
Note: As you have seen earlier, with inline CSS, you can use the color name, Hex code, RGB value, and HSL value with internal or external styling.
Wrapping Up
In this article, you have learned how to change an HTML element’s font/text color using CSS. You also learned how developers did it before the introduction of HTML5 with the <font>
tag and color attributes.
Also, keep in mind that styling your HTML elements with internal or external styling is always preferable to inline styling. This is because it provides more flexibility.
For example, instead of adding similar inline styles to all your <p>
tag elements, you can use a single CSS class
for all of them.
Inline styles are not considered best practices because they result in a lot of repetition — you cannot reuse the styles elsewhere. To learn more, you can read my article on Inline Style in HTML. You can also learn how to change text size in this article and background color in this article.
I hope this tutorial gives you the knowledge to change the color of your HTML text to make it look better.
Have fun coding!
Learn to code for free. freeCodeCamp’s open source curriculum has helped more than 40,000 people get jobs as developers. Get started
Использование цвета — одна из фундаментальных форм человеческого восприятия, так дети экспериментируют с цветом ещё до того, как начинают осознанно рисовать. Возможно, именно поэтому цвет — одна из первых вещей, с которой люди хотят экспериментировать, изучая разработку веб-сайтов. С помощью CSS, существует множество способов присвоить цвет HTML элементам, чтобы придать им желаемый вид. Эта статья даёт базовые представления о всех способах применения цвета к HTML-элементам с помощью CSS.
К счастью, присвоить цвет к HTML-элементу очень просто, и это можно сделать практически со всеми элементами.
Мы затронем большинство из того, что нужно знать при использовании цвета, включая список элементов, которые могут иметь цвет, и необходимые для этого CSS-свойства, как задать цвет, и как использовать его в таблицах стилей и в JS скриптах. Мы также рассмотрим как предоставить возможность пользователю выбрать цвет.
Завершим мы статью размышлениями на тему как использовать цвет с умом: как выбрать подходящий цвет, учитывая потребности людей с различными визуальными способностями.
Что может иметь цвет
На уровне элементов HTML, всему можно присвоить цвет. С точки зрения отдельных составляющих элементов, таких как текст, границы и т.д., существует ряд свойств CSS, с помощью которых можно присвоить цвет.
На фундаментальном уровне, свойство color
(en-US) определяет цвет текста HTML-элемента, а свойство background-color
— цвет фона элемента. Они работают практически для всех элементов.
Текст
Эти свойства используются для определения цвета текста, его фона и любого оформления текста.
color
(en-US)-
Свойство color применяется к тексту и любому оформлению текста, например: подчёркивание, линии на текстом, перечёркивание и т.д.
background-color
-
Цвет фона текста.
text-shadow
-
Добавляет и устанавливает параметры тени для текста. Один из параметров тени — это основной цвет, который размывается и смешивается с цветом фона на основе других параметров. См. Text drop shadows в Fundamental text and font styling, чтобы узнать больше.
text-decoration-color
(en-US)-
По умолчанию, элементы оформление текста (подчёркивание, перечёркивание) используют цвет свойства
color
. Но вы можете присвоить другой цвет с помощью свойстваtext-decoration-color
. text-emphasis-color
(en-US)-
Цвет, который используется для выделения диакритических знаков, прилегающих к каждому текстовому символу. Это свойство используется преимущественно для восточноазиатских языков.
caret-color
(en-US)-
Цвет, который используется для каретки (caret (en-US)) (курсора ввода текста). Применимо только к редактируемым элементам, таким как
<input>
и<textarea>
(en-US) или элементам , для которых установлен атрибутcontenteditable
.
Блоки
Каждый элемент представляет собой прямоугольный блок с каким-то содержимым, фоном и границей.
borders
-
См. раздел Borders с перечнем свойств CSS, с помощью которых можно присвоить цвет границам блока.
background-color
-
Цвет фона блока.
column-rule-color
-
Цвет линий, которые разделяют колонки текста.
outline-color
(en-US)-
Цвет контура, вокруг границы элемента. Этот контур отличается от границы элемента тем, что он не занимает место в документе и может перекрывать другой элемент. Обычно его используют как рамку-индикатор, чтобы показать какой элемент находится в фокусе.
Границы
Вокруг любого элемента можно создать границу (en-US), т.е. линию вокруг содержимого элемента. См. Box properties в The box model, чтобы узнать больше про отношения между элементами и их границами, и статью Оформляем Границы с Помощью CSS (en-US), чтобы узнать больше про то, как применять стили к границам.
Существует краткая запись border
, которая позволяет задать сразу все свойства границы, включая даже не связанные с цветом свойства, такие как толщина линии (width), стиль линии (style (en-US)): сплошная (solid), штриховая (dashed) и так далее.
border-color
(en-US)-
Задаёт единый цвет для всех сторон границы элемента.
border-left-color
(en-US),border-right-color
(en-US),border-top-color
(en-US), andborder-bottom-color
(en-US)-
Позволяет установить цвет соответствующей стороне границы элемента: border-left-color — левая граница, border-right-color — правая, border-top-color — верхняя, border-bottom-color — нижняя.
border-block-start-color
(en-US) andborder-block-end-color
(en-US)-
С помощью этих свойств вы можете установить цвет границ, которые расположены ближе всего к началу и концу блока. Для письменности слева направо, начало границы блока — верхний край, а конец — нижний. Не путайте с началом и концом строки, где начало — это левый край, а конец — правый.
border-inline-start-color
(en-US) andborder-inline-end-color
(en-US)-
Эти свойства определяют цвет границы, расположенной ближе всего к началу и концу текста в блоке. Сторона начала и конца зависит от свойств
writing-mode
,direction
иtext-orientation
(en-US), которые обычно (но не всегда) используются для настройки направления текста. Например, если текст отображается справа налево, тоborder-inline-start-color
применяется к правой стороне границы.
Как можно ещё использовать цвет
CSS не единственная web-технология, которая поддерживает цвет.
- HTML Canvas API
-
Позволяет создавать растровую 2D-графику в элементе
<canvas>
. См. Canvas tutorial, чтобы узнать больше. - SVG (Scalable Vector Graphics — Масштабируемая Векторная Графика)
-
Позволяет создавать изображения с помощью команд, которые рисуют определённые фигуры, узоры, линии для создания конечного изображения. Команды SVG форматируются в XML, и могут размещаться непосредственно на веб-странице, или в элементе
<img>
, как и любое другое изображение. - WebGL
-
Библиотека Веб-Графики (The Web Graphics Library) — это кроссплатформенный API на основе OpenGL ES, используется для создания высокопроизводительной 2D и 3D-графики в браузере. См. Learn WebGL for 2D and 3D, чтобы узнать больше..
Как задать цвет
Для того чтобы задать цвет в CSS, необходимо найти способ как перевести понятие «цвета» в цифровой формат, который может использовать компьютер. Обычно это делают разбивая цвет на компоненты, например какое количество единиц основных цветов содержится в данном цвете или степень яркости. Соответственно, есть несколько способов как можно задать цвет в CSS.
Подробнее о каждом значения цвета, можно прочитать в статье про CSS <color>
.
Ключевые слова
Существует набор названий цветов стандартной палитры, который позволяет использовать ключевые слова вместо числового значения цвета. Ключевые слова включают основные и вторичные цвета (такие как красный (red
), синий (blue
), или оранжевый (orange
)), оттенки серого (от чёрного (black
) к белому (white
), включая такие цвета как темносерый (darkgray
) или светло-серый (lightgrey
)), а также множество других смешанных цветов: lightseagreen
, cornflowerblue
, и rebeccapurple
.
См. Color keywords в <color>
— полный перечень всех доступных ключевых слов.
RGB значения
Есть три способа передачи RGB цвета в CSS.
Шестнадцатеричная запись в виде строки
Шестнадцатеричная запись передаёт цвет, используя шестнадцатеричные числа, которые передают каждый компонент цвета (красный, зелёный и синий). Запись также может включать четвёртый компонент: альфа-канал (или прозрачность). Каждый компонент цвета может быть представлен как число от 0 до 255 (0x00 — 0xFF) или, опционально, как число от 0 до 15 (0x0 — 0xF). Каждый компонент необходимо задавать используя одинаковое количество чисел. Так, если вы используете однозначное число, то итоговый цвет рассчитывается используя число каждого компонента дважды: "#D"
превращается в "#DD"
.
Цвет в шестнадцатеричной записи всегда начинается с символа "#"
. После него начинаются шестнадцатеричные числа цветового кода. Запись не зависит от регистра.
"#rrggbb"
-
Задаёт полностью непрозрачный цвет, у которого компонент красного цвета представлен шестнадцатеричным числом
0xrr
, зелёного —0xgg
и синего —0xbb
. "#rrggbbaa"
-
Задаёт цвет, у которого компонент красного представлен шестнадцатеричным числом
0xrr
, зелёного —0xgg
и синего —0xbb
. Альфа канал представлен0xaa
; чем ниже значение, тем прозрачнее становится цвет. "#rgb"
-
Задаёт цвет, у которого компонент красного представлен шестнадцатеричным числом
0xr
, зелёного —0xg
и синего —0xb
. "#rgba"
-
Задаёт цвет, у которого компонент красного представлен шестнадцатеричным числом
0xr
, зелёного —0xg
и синего —0xb
. Альфа канал представлен0xa
; чем ниже значение, тем прозрачнее становится цвет.
Например, вы можете представить непрозрачный ярко-синий цвет как "#0000ff"
или "#00f"
. Для того, чтобы сделать его на 25% прозрачным, вы можете использовать "#0000ff44"
или "#00f4"
.
RGB запись в виде функции
RGB запись в виде функции, как и шестнадцатеричная запись, представляет цвет, используя красный, зелёный и синий компоненты (также, опционально можно использовать компонент альфа канала для прозрачности). Но, вместо того, чтоб использовать строку, цвет определяется CSS функцией rgb()
. Данная функция принимает как вводные параметры значения красного, зелёного и синего компонентов и, опционально, четвёртого компонента — значение альфа канала.
Допустимые значения для каждого из этих параметров:
red
,green
, иblue
-
Каждый параметр должен иметь
<integer>
значение между 0 и 255 (включительно), или<percentage>
от 0% до 100%. alpha
-
Альфа канал — это числовое значение между 0.0 (полностью прозрачный) и 1.0 (полностью непрозрачный). Также можно указать значение в процентах, где 0% соответствует 0.0, а 100% — 1.0.
Например, ярко-красный с 50% прозрачностью может быть представлен как rgb(255, 0, 0, 0.5)
или rgb(100%, 0, 0, 50%)
.
HSL запись в виде функции
Дизайнеры часто предпочитают использовать цветовую модель HSL, где H — Hue (оттенок), S — Saturation (насыщенность), L — Lightness or Luminance (светлота). В браузерах HSL цвет представлен через запись HSL в виде функции. CSS функция hsl()
очень похожа на rgb()
функцию.
Рис. 1. Цилиндрическая модель HSL. Hue (оттенок) определяет фактический цвет, основанный на положении вдоль цветового круга, представляя цвета видимого спектра. Saturation (насыщенность) представляет собой процентное соотношение оттенка от серого до максимально насыщенного цвета. По мере увеличения значения luminance/ lightness (светлоты) цвет переходит от самого тёмного к самому светлому (от чёрного к белому). Изображение представлено пользователем SharkD в Wikipedia, распространяется на правах лицензии CC BY-SA 3.0 .
Значение компонента оттенок (H) цветовой модели HSL определяется углом при движении вдоль окружности цилиндра от красного через жёлтый, зелёный, голубой, синий и маджента, и заканчивая через 360° снова красным. Данное значение определяет базовый цвет. Его можно задать в любых единицах, поддерживаемых CSS-свойством <angle>
, а именно — в градусах (deg
), радианах (rad
), градиентах (grad
) или поворотах (turn
). Но компонент оттенок никак не влияет на то, насколько насыщенным, ярким или темным будет цвет.
Компонент насыщенность (S) определяет количество конечного цвета из которого состоит указанный оттенок. Остальное определяется уровнем серого цвета, которое указывает компонент luminance/ lightness (L).
Подумайте об этом как о создании идеального цвета краски:
- Вы начинаете с базовой краски, т.е. с максимально возможной интенсивности данного цвета. Например, наиболее насыщенный синий, который может быть представлен на экране пользователя. Это компонент hue (оттенок): значение представляющее угол вокруг цветового круга для насыщенного оттенка, который мы хотим использовать в качестве нашей базы.
- Далее выберете краску серого оттенка, которая будет соответствовать тому, насколько ярким вы хотите сделать цвет. Это luminance/ lightness (яркость). Вы хотите, чтобы цвет был очень ярким, практически белым или очень темным, ближе к чёрному, или что-то среднее? Данный компонент определяется в процентах, где 0% — совершенный чёрный цвет и 100% — совершенный белый (независимо от насыщенности или оттенка). Средние значения — это буквальная серая область.
- Теперь, когда у есть серый цвет и идеально насыщенный цвет, вам необходимо их смешать. Компонент saturation (насыщенность) определяет какой процент конечного цвета должен состоять из идеально насыщенного цвета. Остаток конечного цвета формируется серым цветом, который представляет насыщенность.
Опционально вы также можете включить альфа-канал, чтобы сделать цвет менее прозрачным.
Вот несколько примеров цвета в HSL записи:
table {
border: 1px solid black;
font: 16px "Open Sans", Helvetica, Arial, sans-serif;
border-spacing: 0;
border-collapse: collapse;
}
th, td {
border: 1px solid black;
padding:4px 6px;
text-align: left;
}
th {
background-color: hsl(0, 0%, 75%);
}
<table>
<thead>
<tr>
<th scope="col">Color in HSL notation</th>
<th scope="col">Example</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>hsl(90deg, 100%, 50%)</code></td>
<td style="background-color: hsl(90deg, 100%, 50%);"> </td>
</tr>
<tr>
<td><code>hsl(90, 100%, 50%)</code></td>
<td style="background-color: hsl(90, 100%, 50%);"> </td>
</tr>
<tr>
<td><code>hsl(0.15turn, 50%, 75%)</code></td>
<td style="background-color: hsl(0.15turn, 50%, 75%);"> </td>
</tr>
<tr>
<td><code>hsl(0.15turn, 90%, 75%)</code></td>
<td style="background-color: hsl(0.15turn, 90%, 75%);"> </td>
</tr>
<tr>
<td><code>hsl(0.15turn, 90%, 50%)</code></td>
<td style="background-color: hsl(0.15turn, 90%, 50%);"> </td>
</tr>
<tr>
<td><code>hsl(270deg, 90%, 50%)</code></td>
<td style="background-color: hsl(270deg, 90%, 50%);"> </td>
</tr>
</tbody>
</table>
Примечание: Обратите внимание, что, когда вы не указываете единицу измерения оттенка (hue), то предполагается, что он указан в градусах (deg
).
Использование цвета
Теперь, когда вы знаете какие существуют свойства CSS для присваивания цвета к элементам и какие есть форматы описания цвета, вы можете соединить это вместе, чтобы начать использовать цвет. Как вы уже видели в списке под разделом Что может иметь цвет, существует множество вещей, к которым можно применить цвет, используя CSS. Давайте взглянем на это с двух сторон: использовать цвет в таблицах стилей (stylesheet (en-US)) и добавлять, изменять цвет, используя JavaScript код.
Цвет в таблицах стилей CSS
Самый простой способ присвоить цвет элементу и то, как это обычно делается — это просто указать цвет в CSS. Мы не будем останавливаться на каждом из вышеупомянутых свойств, а просто рассмотрим несколько примеров. Где бы вы не использовали цвет, принцип один и тот же.
Давайте начнём наш пример с результата, который нам нужно достичь:
HTML
HTML, который создаёт вышеупомянутый пример:
<div class="wrapper">
<div class="box boxLeft">
<p>
This is the first box.
</p>
</div>
<div class="box boxRight">
<p>
This is the second box.
</p>
</div>
</div>
Все довольно просто: первый <div>
используется как обёртка (wrapper) содержимого, которое состоит из ещё двух <div>
, каждый из которых содержит один параграф (<p>
) и имеет свой стиль.
Все волшебство, как всегда, происходит в CSS, где мы и будем присваивать цвет к данным HTML-элементам..
CSS
CSS мы рассмотрим более детально, чтобы по очереди проанализировать все интересные части.
.wrapper {
width: 620px;
height: 110px;
margin: 0;
padding: 10px;
border: 6px solid mediumturquoise;
}
Класс .wrapper
определяет стиль для элемента <div>
, который заключает в себе все остальные элементы. Он устанавливает размер контейнера с помощью свойств ширины width
, высоты height
, внешних margin
и внутренних padding
полей.
Но больше всего нас интересует свойство граница border
, которое устанавливает границу вокруг внешнего края элемента. Данная граница представлена сплошной линией, шириной в 6 пикселей, светло-бирюзового цвета (mediumturquoise
).
Два цветных блока имеют ряд одинаковых свойств, поэтому далее мы установим класс .box
, который определит эти общие свойства:
.box {
width: 290px;
height: 100px;
margin: 0;
padding: 4px 6px;
font: 28px "Marker Felt", "Zapfino", cursive;
display: flex;
justify-content: center;
align-items: center;
}
Вкратце класс .box
устанавливает размер каждого блока и параметры шрифта. Также мы используем CSS Flexbox, чтобы с лёгкостью отцентрировать содержимое каждого блока. Мы включаем режим flex
с помощью display: flex
, и присваиваем значение center justify-content
и align-items
. Затем мы создаём отдельные классы для каждого из двух блоков, которые определят индивидуальные свойства.
.boxLeft {
float: left;
background-color: rgb(245, 130, 130);
outline: 2px solid darkred;
}
Класс .boxLeft
, который используется для стилизации левого блока, выравнивает контейнер по левому краю и присваивает цвета:
background-color
определяет цвет фона блока значениемrgb(245, 130, 130)
.outline
(en-US), в отличие от привычного нам свойстваborder
, не влияет на положение блока и его ширину.Outline
представлен сплошной, темно-красной линией, шириной в 2 пикселя. Обратите внимание на ключевое словоdarkred
, которое используется для определение цвета.- Обратите внимание, что мы не определяем значение цвета текста. Это означает, что свойство
color
(en-US) будет унаследовано от ближайшего родительского элемента, у которого это свойство определено. По умолчанию это чёрный цвет.
.boxRight {
float: right;
background-color: hsl(270deg, 50%, 75%);
outline: 4px dashed rgb(110, 20, 120);
color: hsl(0deg, 100%, 100%);
text-decoration: underline wavy #88ff88;
text-shadow: 2px 2px 3px black;
}
Класс .boxRight
описывает свойства правого блока. Блок выравнивается по правому краю и становится рядом с предыдущим блоком. Затем определяются следующие цвета:
background-color
определяется значением HSL:hsl(270deg, 50%, 75%)
. Это светло-фиолетовый цвет.Outline
блока определяет, что вокруг блока должна быть прерывистая линия, шириной в четыре пикселя, фиолетового цвета немного темнее, чем цвет фона (rgb(110, 20, 120)
).- Цвет текста определяется свойством
color
(en-US), значение которогоhsl(0deg, 100%, 100%)
. Это один из многих способов задать белый цвет. - С помощью
text-decoration
(en-US) мы добавляем зелёную волнистую линию под текстом. - И наконец, свойство
text-shadow
добавляет небольшую чёрную тень тексту.
Предоставляем возможность пользователю выбрать цвет
There are many situations in which your web site may need to let the user select a color. Perhaps you have a customizable user interface, or you’re implementing a drawing app. Maybe you have editable text and need to let the user choose the text color. Or perhaps your app lets the user assign colors to folders or items. Although historically it’s been necessary to implement your own color picker, HTML now provides support for browsers to provide one for your use through the <input>
element, by using "color"
as the value of its type
attribute.
The <input>
element represents a color only in the hexadecimal string notation covered above.
Example: Picking a color
Let’s look at a simple example, in which the user can choose a color. As the user adjusts the color, the border around the example changes to reflect the new color. After finishing up and picking the final color, the color picker’s value is displayed.
Примечание: On macOS, you indicate that you’ve finalized selection of the color by closing the color picker window.
HTML
The HTML here creates a box that contains a color picker control (with a label created using the <label>
element) and an empty paragraph element (<p>
) into which we’ll output some text from our JavaScript code.
<div id="box">
<label for="colorPicker">Border color:</label>
<input type="color" value="#8888ff" id="colorPicker">
<p id="output"></p>
</div>
CSS
The CSS simply establishes a size for the box and some basic styling for appearances. The border is also established with a 2-pixel width and a border color that won’t last, courtesy of the JavaScript below…
#box {
width: 500px;
height: 200px;
border: 2px solid rgb(245, 220, 225);
padding: 4px 6px;
font: 16px "Lucida Grande", "Helvetica", "Arial", "sans-serif"
}
JavaScript
The script here handles the task of updating the starting color of the border to match the color picker’s value. Then two event handlers are added to deal with input from the <input type="color">
element.
let colorPicker = document.getElementById("colorPicker");
let box = document.getElementById("box");
let output = document.getElementById("output");
box.style.borderColor = colorPicker.value;
colorPicker.addEventListener("input", function(event) {
box.style.borderColor = event.target.value;
}, false);
colorPicker.addEventListener("change", function(event) {
output.innerText = "Color set to " + colorPicker.value + ".";
}, false);
The input (en-US)
event is sent every time the value of the element changes; that is, every time the user adjusts the color in the color picker. Each time this event arrives, we set the box’s border color to match the color picker’s current value.
The change (en-US)
event is received when the color picker’s value is finalized. We respond by setting the contents of the <p>
element with the ID "output"
to a string describing the finally selected color.
Using color wisely
Making the right choices when selecting colors when designing a web site can be a tricky process, especially if you aren’t well-grounded in art, design, or at least basic color theory. The wrong color choice can render your site unattractive, or even worse, leave the content unreadable due to problems with contrast or conflicting colors. Worse still, if using the wrong colors can result in your content being outright unusable by people withcertain vision problems, particularly color blindness.
Finding the right colors
Coming up with just the right colors can be tricky, especially without training in art or design. Fortunately, there are tools available that can help you. While they can’t replace having a good designer helping you make these decisions, they can definitely get you started.
Base color
The first step is to choose your base color. This is the color that in some way defines your web site or the subject matter of the site. Just as we associate green with the beverage Mountain Dew and one might think of the color blue in relationship with the sky or the ocean, choosing an appropriate base color to represent your site is a good place to start. There are plenty of ways to select a base color; a few ideas include:
- A color that is naturally associated with the topic of your content, such as the existing color identified with a product or idea or a color representative of the emotion you wish to convey.
- A color that comes from imagery associated with what your content is about. If you’re creating a web site about a given item or product, choose a color that’s physically present on that item.
- Browse web sites that let you look at lots of existing color palettes and imags to find inspiration.
When trying to decide upon a base color, you may find that browser extensions that let you select colors from web content can be particularly handy. Some of these are even specifically designed to help with this sort of work. For example, the web site ColorZilla offers an extension (Chrome / Firefox) that offers an eyedropper tool for picking colors from the web. It can also take averages of the colors of pixels in various sized areas or even a selected area of the page.
Примечание: The advantage to averaging colors can be that often what looks like a solid color is actually a surprisingly varied number of related colors all used in concert, blending to create a desired effect. Picking just one of these pixels can result in getting a color that on its own looks very out of place.
Fleshing out the palette
Once you have decided on your base color, there are plenty of online tools that can help you build out a palette of appropriate colors to use along with your base color by applying color theory to your base color to determine appropriate added colors. Many of these tools also support viewing the colors filtered so you can see what they would look like to people with various forms of color blindness. See Color and accessibility for a brief explanation of why this matters.
A few examples (all free to use as of the time this list was last revised):
- MDN’s color picker tool
- Paletton
- Adobe Color CC online color wheel
When designing your palette, be sure to keep in mind that in addition to the colors these tools typically generate, you’ll probably also need to add some core neutral colors such as white (or nearly white), black (or nearly black), and some number of shades of gray.
Примечание: Usually, you are far better off using the smallest number of colors possible. By using color to accentuate rather than adding color to everything on the page, you keep your content easy to read and the colors you do use have far more impact.
Color theory resources
A full review of color theory is beyond the scope of this article, but there are plenty of articles about color theory available, as well as courses you can find at nearby schools and universities. A couple of useful resources about color theory:
- Color Science (Khan Academy in association with Pixar)
-
An online course which introduces concepts such as what color is, how it’s percieved, and how to use colors to express ideas. Presented by Pixar artists and designers.
- Color theory on Wikipedia
-
Wikipedia’s entry on color theory, which has a lot of great information from a technical perspective. It’s not really a resource for helping you with the color sleection process, but is still full of useful information.
Color and accessibility
There are several ways color can be an accessibility problem. Improper or careless use of color can result in a web site or app that a percentage of your target audience may not be able to use adequately, resulting in lost traffic, lost business, and possibly even a public relations problem. So it’s important to consider your use of color carefully.
You should do at least basic research into color blindness. There are several kinds; the most common is red-green color blindness, which causes people to be unable to differentiate between the colors red and green. There are others, too, ranging from inabilities to tell the difference between certain colors to total inability to see color at all.
Примечание: The most important rule: never use color as the only way to know something. If, for example, you indicate success or failure of an operation by changing the color of a shape from white to green for success and red for failure, users with red-green color-blindness won’t be able to use your site properly. Instead, perhaps use both text and color together, so that everyone can understand what’s happening.
For more information about color blindness, see the following articles:
- Medline Plus: Color Blindness (United States National Institute of Health)
- American Academy of Ophthamology: What Is Color Blindness?
- Color Blindness & Web Design (Usability.gov: United States Department of Health and Human Services)
Palette design example
Let’s consider a quick example of selecting an appropriate color palette for a site. Imagine that you’re building a web site for a new game that takes place on the planet Mars. So let’s do a Google search for photos of Mars. Lots of good examples of Martian coloration there. We carefully avoid the mockups and the photos from movies. And we decide to use a photo taken by one of the Mars landers humanity has parked on the surface over the last few decades, since the game takes place on the planet’s surface. We use a color picker tool to select a sample of the color we choose.
Using an eyedropper tool, we identify a color we like and determine that the color in question is #D79C7A
, which is an appropriate rusty orange-red color that’s so stereotypical of the Martian surface.
Having selected our base color, we need to build out our palette. We decide to use Paletteon to come up with the other colors we need. Upon opening Paletton, we see:
Next, we enter our color’s hex code (D79C7A
) into the «Base RGB» box at the bottom-left corner of the tool:
We now see a monochromatic palette based on the color we picked from the Mars photo. If you need a lot of related colors for some reason, those are likely to be good ones. But what we really want is an accent color. Something that will pop along side the base color. To find that, we click the «add complementary» toggle underneath the menu that lets you select the palette type (currently «Monochromatic»). Paletton computes an appropriate accent color; clicking on the accent color down in the bottom-right corner tells us that this color is #508D7C
.
If you’re unhappy with the color that’s proposed to you, you can change the color scheme, to see if you find something you like better. For example, if we don’t like the proposed greenish-blue color, we can click the Triad color scheme icon, which presents us with the following:
That greyish blue in the top-right looks pretty good. Clicking on it, we find that it’s #556E8D
. That would be used as the accent color, to be used sparingly to make things stand out, such as in headlines or in the highlighting of tabs or other indicators on the site:
Now we have our base color and our accent. On top of that, we have a few complementary shades of each, just in case we need them for gradients and the like. The colors can then be exported in a number of formats so you can make use of them.
Once you have these colors, you will probably still need to select appropriate neutral colors. Common design practice is to try to find the sweet spot where there’s just enough contrast that the text is crisp and readable but not enough contrast to become harsh for the eyes. It’s easy to go too far in one way or another so be sure to get feedback on your colors once you’ve selected them and have examples of them in use available. If the contrast is too low, your text will tend to be washed out by the background, leaving it unreadable, but if your contrast is too high, the user may find your site garish and unpleasant to look at.
See also
3 октября, 2020 11:49 дп
2 260 views
| Комментариев нет
Development
Эта серия мануалов поможет вам создать и настроить веб-сайт с помощью HTML, стандартного языка разметки, используемого для отображения документов в браузере. Для работы с этими мануалами не требуется предварительный опыт программирования.
В результате выполнения этой серии у вас будет веб-сайт, готовый к развертыванию в облаке, также вы получите базовые знания HTML. Умение писать HTML – хорошая основа для изучения более сложных аспектов веб-разработки, таких как CSS и JavaScript.
Примечание: Найти все мануалы этой серии можно по тегу html-practice.
HTML позволяет менять цвета некоторых элементов и частей содержимого веб-страницы. Например, так вы можете изменить цвет текста, границы или элемента <div>.
Читайте также: Как работает <div>, элемент разделения контента HTML
Метод изменения цвета этих частей варьируется от элемента к элементу.
В этом мануале вы узнаете, как изменить цвет текста, границ изображения и элементов <div>, используя названия цветов HTML.
Цвет текстовых элементов (типа <p> или <h1>) изменяется с помощью атрибута style и свойства color. Это делается следующим образом:
<p style="color:blue;">This is blue text.</p>
Попробуйте записать этот код в файл index.html и загрузить его в браузере. Примечание: Если вы работали с этой серией мануалов непоследовательно, рекомендуем обратиться к статье Подготовка HTML-проекта, чтобы создать файл index.html.
Вы должны получить такой результат:
This is blue text.
Цвет границы изображения изменяется с помощью атрибута style и свойства border:
<img src="https://www.8host.com/blog/wp-content/themes/wp-8host-new/img/logo.svg" style="border: 10px solid lime"/>
Здесь мы поместили ссылку на изображение и указали, что граница должна быть шириной 10 пикселей и сплошной (solid
), а не пунктирной.
Попробуйте вставить этот код в файл index.html и загрузить его в браузере.
Примечание: Обратите внимание, что в этом примере мы используем изображение, которое уже размещено в Интернете.
Вы должны получить такой результат:
Цвет контейнера <div> изменяется с помощью атрибута style и свойства background-color. Это можно сделать следующим образом:
<div style="width:200px;height:200px;background-color:yellow;"></div>
Попробуйте написать этот код в файле index.html и загрузить его в браузере. Вы должны получить такой результат:
Во всех этих примерах значение цвета определяется названиями цветов. Попробуйте изменить цвет текста, границ изображения и элементов <div>, используя названия других цветов:
- black
- white
- gray
- silver
- purple
- red
- fuchsia
- lime
- olive
- green
- yellow
- teal
- navy
- blue
- maroon
- aqua
Цвета также можно указывать в шестнадцатеричном формате. Шестнадцатеричный код цвета состоит из шести буквенно-цифровых символов, перед которыми идет диез, например:
- #0000FF (синий),
- #40E0D0 (бирюзовый)
- #C0C0C0 (серебристый)
Примечание: В этой серии мануалов мы продолжим использовать названия цветов, а не шестнадцатеричный код.
Теперь у вас есть базовые знания о том, как изменять цвет текста, границ изображения и элементов <div>. Мы вернемся к работе с цветами чуть позже, когда начнем создавать наш веб-сайт.
Tags: HTML, HTML-practice
Цвет текста на странице можно задать несколькими способами! Если требуется изменить цвет текста на другой, то достаточно добавить стиль к какой-то части текста, либо ко всему тексту и цвет текста изменится на вами установленный.
Цвет текста css по умолчанию?
С самого начала — давайте разберемся, что вообще означает «Цвет текста css по умолчанию«:
Это такой цвет текста, который изначально установлен для всех(либо вами выбранных) элементов сайта и который срабатывает при загрузке страницы.
Какой цвет установлен по умолчанию?
Если вы создадите простую страницу и добавите туда текст, без указания цвета текста, то он будет отображаться как черный (black).
Сделал специально страницу о заранее предопределенных цветах, т.е. цвета определены цветом!
Например красный — red
Как еще можно подобрать цвет текста!?
Не обязательно это может быть цвет «словом» — цвет может быть задан буквенно цифровым способом -> в онлайн генераторе цветов.
Как обозначается цвет в css?
Цвет в css пишется английское слово «color» — которое перевоимся как «цвет» и через двоеточие пишется цвет, например:
color : red ;
Как используется цвет в стилях css!?
Существует «3 способа css» задать цвет тексту через css!
Пример — как можно изменить цвет по умолчанию
На сайте установлен некий цвет текста по умолчанию — сделаем стенд, по нажатию на кнопку вы можете изменить этот цвет по умолчанию!
И! — изменится только тот цвет по умолчанию, который никак отдельным образом не прописан — чтобы это проверить нажми на кнопку:
Задать цвет текста внутри тега
Цвет текста может быть задан внутри тега!
Предположим, что нам нужно задать какой то цвет тексту в теге…
Для этого нам понадобится какой-то тег, пусть это будет — span
<span></span>
Внутрь первого тега помещаем атрибут «style» со значением цвет -> «color» и определяем цвет, путь это будет фиолетовый -> color:violet
<span style=»color:violet;»>Здесь текст, который будет покрашен в цвет color:violet</span>
Результат :
Мы задали нашему тексту цвет фиолетовый:
Здесь текст, который будет покрашен в цвет color:violet
Как изменить цвет текста
Если нам требуется изменить цвет текста на любой другой, то мы должны первым делом найти цвет одним из способов:
После этого берем выше приведенный тег и меняем цвет внутри тега:
<span style=»color : firebrick ;»>Здесь текст, который будет покрашен в цвет firebrick </span>
Здесь текст, который будет покрашен в цвет color: firebrick
Задать свой собственный тег для цвета текста
Если вы часто используете изменение цвета текста на сайте, для разных целей, то вы наверное понимаете, что написать
<span style=»color: red ;»>Здесь текст, который будет покрашен в цвет red</span>
и например цвет текста в собственном теге, намного проще… :
<red>Здесь текст, который будет покрашен в цвет red</red>
Результат изменения цвета текста в теге
Здесь текст, который будет покрашен в цвет red
Или же путь это будет зеленый цвет:
<green>Здесь текст, который будет покрашен в цвет green</green>
Здесь текст, который будет покрашен в цвет green
Как создать такой тег, для изменения цвета текста!?
В стилях css
записываем таким образом:
Тоже самое для любого другого цвета
Способ задать цвет тексту на странице через стили
Для того, чтобы задать цвет тексту можно воспользоваться стилями на одной странице! Этот способ подходит в тех случаях, когда требуется задать/изменить цвет текста только на это странице!
Нам понадобится тег style :
<style></style>
Располагаем данный стиль в любом месте на странице, лучше всего его располагать внутри тега head :
<head></head>
Создадим новый тег, который у нас не используется на сайте, пусть это будет violet, задаем ему цвет violet :
<style>
violet{
color: violet;
}
</style>
Внутри тега violet помещаем текст,чтобы мы могли его увидеть!
<violet>Цвет текста violet </violet>
Результат, цвет для текста задан через стили на странице:
Цвет текста violet
Задать цвет тексту через файл css
Для того, чтобы задать цвет текста через файл css -повторяем все операции, как и пункте 2, только в файле стилей!
Задать цвет тексту через class
Для того, чтобы задать цвет текста через класс, нужно создать стили для этого класса:
Класс пишется, обычно латинскими буквами и перед ним ставится точка, что и означает класс:
.example
После класса используются двойные фигурные скобки:
{}
Внутри скобок прописываются цвет для текста:
.example { color: maroon;}
Далее нужно прикрепить данный класс к тегу:
<div class=»example»>Здесь текст</div>
Результат:
Здесь текст class=»example»
Задать цвет тексту через id
Для того, чтобы задать цвет текста через id, нужно создать стили для этого id:
Все тоже самое. что и для класса, лишь изменяется точка на решетку,
«.» -> «#»
и слово «class» на «id»
id пишется, обычно латинскими буквами и перед ним ставится решетка, что и означает id :
#example
После идентификатора используются двойные фигурные скобки:
{}
Внутри скобок прописываются цвет для текста:
#example { color: cyan;}
Далее нужно прикрепить данный id к тегу:
<div id=»example»>Здесь текст</div>
Результат:
Один из поисковых запросов : «как сделать чтобы текст выводился белый в css«…
Используем ранее выведенную теорию. Для этого вам понадобится :
Html:
<blackblock style="color: white;">Здесь ваш белый текст</blackblock>
Css:
blackblock {
background: black;
color: white;
}