Язык html как изменить цвет

Как изменить цвет текста в HTML. В HTML цвет текста меняется с помощью тега , но этот метод больше не поддерживается в HTML5. Вместо указанного тега нужно пользоваться CSS, чтобы задать цвет текста различных элементов страницы....


Загрузить PDF


Загрузить PDF

В HTML цвет текста меняется с помощью тега <font>, но этот метод больше не поддерживается в HTML5. Вместо указанного тега нужно пользоваться CSS, чтобы задать цвет текста различных элементов страницы. Использование CSS гарантирует, что веб-страница будет совместима с любым браузером.

  1. 1

    Откройте файл HTML. Лучший способ изменить цвет текста — это воспользоваться CSS. Старый тег <font> больше не поддерживается в HTML5. Поэтому воспользуйтесь CSS, чтобы определить стиль элементов страницы.

    • Этот метод также применим к внешним таблицам стилей (отдельным файлам CSS). Приведенные ниже примеры предназначены для файла HTML с внутренней таблицей стилей.
  2. 2

    Размеcтите курсор внутри тега <head>. Стили определяются внутри этого тега, если используется внутренняя таблица стилей.

  3. 3

    Введите <style>, чтобы создать внутреннюю таблицу стилей. Когда тег <style> находится внутри тега <head>, таблица стилей, которая находится внутри тега <style>, будет применена к любым элементам страницы. Таким образом, начало HTML-файла должно выглядеть следующим образом:[1]

    <!DOCTYPE html>
    <html>
    <head>
    <style>
    
    </style>
    </head>
    
  4. 4

    Введите элемент, цвет текста которого нужно изменить. Используйте раздел <style>, чтобы определить внешний вид элементов страницы. Например, чтобы изменить стиль всего текста на странице, введите следующее:

    <!DOCTYPE html>
    <html>
    <head>
    <style>
    body {
    
    }
    </style>
    </head>
    
  5. 5

    В селекторе элемента введите атрибут color:. Этот атрибут определяет цвет текста выбранного элемента. В нашем примере этот атрибут изменит цвет основного текста, который является элементом, включающим весь текст на странице:

    <!DOCTYPE html>
    <html>
    <head>
    <style>
    body {
    	color:
    }
    </style>
    </head>
    
  6. 6

    Введите цвет текста. Это можно сделать тремя способами: ввести имя, ввести шестнадцатеричное значение или ввести значение RGB. Например, чтобы сделать текст синим, введите blue, rgb(0, 0, 255) или #0000FF.

    <!DOCTYPE html>
    <html>
    <head>
    <style>
    body {
    	color: red;
    }
    </style>
    </head>
    
  7. 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. 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. 1

    Откройте файл HTML. Можно воспользоваться атрибутами встроенного стиля, чтобы изменить стиль одного элемента страницы. Это может быть полезно, если нужно внести одно-два изменения в стиль, но не рекомендуется для широкомасштабного применения. Чтобы полностью изменить стиль, используйте предыдущий метод.[2]

  2. 2

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

    <!DOCTYPE html>
    <html>
    <body>
    
    <h1>Этот заголовок нужно изменить</h1>
    
    </body>
    </html>
    
  3. 3

    К элементу добавьте атрибут стиля. Внутри открывающего тега изменяемого элемента введите style="":

    <!DOCTYPE html>
    <html>
    <body>
    
    <h1 style="">Этот заголовок нужно изменить</h1>
    
    </body>
    </html>
    
  4. 4

    Внутри "" введите color:. Например:

    <!DOCTYPE html>
    <html>
    <body>
    
    <h1 style="color:">Этот заголовок нужно изменить </h1>
    
    </body>
    </html>
    
  5. 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 раз.

Была ли эта статья полезной?

Использование цвета — одна из фундаментальных форм человеческого восприятия, так дети экспериментируют с цветом ещё до того, как начинают осознанно рисовать. Возможно, именно поэтому цвет — одна из первых вещей, с которой люди хотят экспериментировать, изучая разработку веб-сайтов. С помощью 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), and border-bottom-color (en-US)

Позволяет установить цвет соответствующей стороне границы элемента: border-left-color — левая граница, border-right-color — правая, border-top-color — верхняя, border-bottom-color — нижняя.

border-block-start-color (en-US) and border-block-end-color (en-US)

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

border-inline-start-color (en-US) and border-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() функцию.

HSL color cylinder

Рис. 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).

Подумайте об этом как о создании идеального цвета краски:

  1. Вы начинаете с базовой краски, т.е. с максимально возможной интенсивности данного цвета. Например, наиболее насыщенный синий, который может быть представлен на экране пользователя. Это компонент hue (оттенок): значение представляющее угол вокруг цветового круга для насыщенного оттенка, который мы хотим использовать в качестве нашей базы.
  2. Далее выберете краску серого оттенка, которая будет соответствовать тому, насколько ярким вы хотите сделать цвет. Это luminance/ lightness (яркость). Вы хотите, чтобы цвет был очень ярким, практически белым или очень темным, ближе к чёрному, или что-то среднее? Данный компонент определяется в процентах, где 0% — совершенный чёрный цвет и 100% — совершенный белый (независимо от насыщенности или оттенка). Средние значения — это буквальная серая область.
  3. Теперь, когда у есть серый цвет и идеально насыщенный цвет, вам необходимо их смешать. Компонент 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%);">&nbsp;</td>
  </tr>
  <tr>
   <td><code>hsl(90, 100%, 50%)</code></td>
   <td style="background-color: hsl(90, 100%, 50%);">&nbsp;</td>
  </tr>
  <tr>
   <td><code>hsl(0.15turn, 50%, 75%)</code></td>
   <td style="background-color: hsl(0.15turn, 50%, 75%);">&nbsp;</td>
  </tr>
  <tr>
   <td><code>hsl(0.15turn, 90%, 75%)</code></td>
   <td style="background-color: hsl(0.15turn, 90%, 75%);">&nbsp;</td>
  </tr>
  <tr>
   <td><code>hsl(0.15turn, 90%, 50%)</code></td>
   <td style="background-color: hsl(0.15turn, 90%, 50%);">&nbsp;</td>
  </tr>
  <tr>
   <td><code>hsl(270deg, 90%, 50%)</code></td>
   <td style="background-color: hsl(270deg, 90%, 50%);">&nbsp;</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:

Right after loading Paletton.

Next, we enter our color’s hex code (D79C7A) into the «Base RGB» box at the bottom-left corner of the tool:

After entering base color

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.

Now with complementary colors included.

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:

Triad color scheme selected

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:

Triad color scheme selected

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


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. Image titled 157292 1 1

    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. Image titled 157292 2 1

    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. Image titled 157292 3 1

    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. Image titled 157292 4 1

    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. Image titled 157292 5 1

    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. Image titled 157292 6 1

    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. Image titled 157292 7 1

    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. Image titled 157292 8 1

    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>
    
  9. Advertisement

  1. Image titled 157292 9 1

    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. Image titled 157292 10 1

    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. Image titled 157292 11 1

    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. Image titled 157292 12 1

    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. Image titled 157292 13 1

    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>
    
  6. Advertisement

Add New Question

  • Question

    How would I type bold font in html?

    Community Answer

    <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?

    Community Answer

    Use the bgcolor attribute with body tag.

  • Question

    How do I change the color of the background?

    Community Answer

    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,982,455 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. Image titled 157292 1 1

    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. Image titled 157292 2 1

    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. Image titled 157292 3 1

    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. Image titled 157292 4 1

    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. Image titled 157292 5 1

    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. Image titled 157292 6 1

    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. Image titled 157292 7 1

    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. Image titled 157292 8 1

    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>
    
  9. Advertisement

  1. Image titled 157292 9 1

    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. Image titled 157292 10 1

    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. Image titled 157292 11 1

    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. Image titled 157292 12 1

    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. Image titled 157292 13 1

    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>
    
  6. Advertisement

Add New Question

  • Question

    How would I type bold font in html?

    Community Answer

    <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?

    Community Answer

    Use the bgcolor attribute with body tag.

  • Question

    How do I change the color of the background?

    Community Answer

    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,982,455 times.

Is this article up to date?

How to Change Text Color in HTML – Font Style Tutorial

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

Цвет шрифта на сайте можно задать при помощи 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% для слова «Нубекс».

Опубликовано: 29.09.2010 Последняя правка: 08.12.2015

Меняем цвет текста и фона

В этом уроке вы узнаете, как менять цвет фона и текста любых элементов HTML-страницы. Вообще, в языке HTML у некоторых тегов есть специальные атрибуты меняющие цвет, например bgcolor (цвет фона). Но, во-первых, эти атрибуты являются устаревшими (думаю помните, что это значит), а во-вторых, как я уже сказал, они есть не у всех тегов. И вот, допустим, вы захотели изменить цвет фона у параграфа текста. И как вы это будете делать, ведь у тега <P> нет такого атрибута? Поэтому, как и в предыдущих уроках, мы будем использовать стили (CSS), то есть универсальный атрибут style, который позволит нам менять цвет там, где мы захотим.

Как можно указывать цвет?

Цвета в HTML (и CSS) можно указывать несколькими способами, я покажу вам самые популярные и распространенные:

  • Имя цвета — В HTML имеется большой список цветов с именами и для того, чтобы указать цвет, достаточно написать его имя на английском, например: red, green, blue.
  • HEX-код цвета — Абсолютно любой цвет можно получить, смешав в разных пропорциях три базовых цвета — красный, зеленый и синий. HEX-код — это три пары шестнадцатеричных значений отвечающих за количество этих цветов в каждом цвете. Перед кодом цвета необходимо поставить знак решетка (#), например: #FF8C00, #CC3300 и так далее.

Раньше в HTML рекомендовалось использовать только безопасную палитру цветов, которая гарантированно отображалась во всех браузерах и на всех мониторах одинаково. Но сегодня ей ограничиваться совершенно не обязательно, так как и браузеры и мониторы давно научились правильно отображать гораздо больший список цветов. А вот указывать цвета по именам я вам как раз и не рекомендую, дело в том, что многие браузеры до сих пор с одним и тем же именем связывают разные цвета. Поэтому в данном учебнике я буду всегда использовать именно HEX-коды цветов.

Как изменить цвет текста?

Чтобы изменить цвет текста в любом элементе HTML-страницы надо указать внутри тега атрибут style. Общий синтаксис следующий:

<тег style=«color:имя цвета»>…</тег> — указание цвета текста по имени.

<тег style=«color:#HEX-код»>…</тег> — указание цвета текста по коду.

И как обычно, чтобы изменить цвет текста на всей странице — достаточно указать атрибут style в теге <BODY>. А если необходимо изменить цвет шрифта для фрагмента текста, то заключите его в тег <SPAN> и примените атрибут к нему.

Пример изменения цвета текста

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "https://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=Windows-1251">
<title>Изменение цвета текста</title>
</head>
<body>
<h5 style="color:#FF0000">Красный текст заголовка</h5>

<p style="color:#0000FF">Синий текст параграфа.</p>

<p>
 <em style="color:#008000">Зеленый курсив.</em>
 <span style="color:#FF0000">Красный текст.</span> 
</p>
</body>
</html>

Результат в браузере

Красный текст заголовка

Синий текст параграфа.

Зеленый курсив. Красный текст.

Как изменить цвет фона?

Цвет фона любого элемента страницы меняется также с помощью атрибута style. Общий синтаксис такой:

<тег style=«background:имя цвета»>…</тег> — указание цвета фона по имени.

<тег style=«background:#HEX-код»>…</тег> — указание цвета фона по коду.

Пример изменения цвета фона

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "https://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=Windows-1251">
<title>Изменение цвета фона</title>
</head>
<body style="background:#CCCCFF">
<h5 style="background:#FFCCCC">Заголовок.</h5>

<p style="background:#CCFFCC">Параграф.</p>

<p>
 <b style="background:#FFFFCC">Жирный текст.</b>
 <span style="background:#FFFFCC">Обычный текст.</span> 
</p>
</body>
</html>

Результат в браузере

Заголовок.

Параграф.

Жирный текст. Обычный текст.

Когда меняешь цвет фона элементов, то становится очень хорошо видно, какую на самом деле ширину занимает каждый из них. Как видите, блочные элементы, такие как параграфы и заголовки, в основном занимают всю доступную ширину, даже если они содержат очень мало текста, а вот встроенные (inline) теги по ширине равны своему содержимому. Кстати, последний параграф в примере тоже занимает всю ширину, просто его фон прозрачный, поэтому сквозь него виден фон страницы. Вообще, фон всех элементов на странице, в которых он не указан явно — прозрачный, вот и все.

Домашнее задание.

  1. Создайте заголовок статьи и двух ее разделов. Напишите в начале статьи и каждом разделе по одному параграфу.
  2. Установите на всей странице шрифт Courier с размером 16px, у заголовка статьи — 22px, а у подзаголовков по 19px.
  3. Пусть у заголовка статьи будет цвет текста #0000CC, а у подзаголовков — #CC3366.
  4. Выделите фоновым цветом #66CC33 два слова во втором параграфе. А в третьем параграфе этим же цветом, но одно подчеркнутое слово.
  5. Не забывайте о том, что значения атрибута style можно группировать, ставя между ними точку с запятой (;).

Посмотреть результат → Посмотреть ответ

When it comes to customizing your site, font color often gets overlooked. In most cases, website owners leave the default font color like black or whatever their theme styles have defined for the body and heading text color.

However, it’s a good idea to change the HTML font color on your website for several reasons. Changing the HTML font color might seem daunting, but it’s pretty simple. There are several ways to change the font color on your website.

In this post, we’ll show you different ways to change the color of your website fonts, as well as discuss why you’d want to do it in the first place.

Check Out Our Video Guide to Changing the HTML Font Color

Why Change the HTML Font Color?

You would want to change the font color because doing so can help improve your website’s readability and accessibility. For example, if your site uses a darker color scheme, leaving the font color black would make it difficult to read the text on your website.

Another reason you would want to consider changing the font color is if you’re going to use a darker color from your brand color palette. This is yet another opportunity to reinforce your brand. It builds brand consistency and ensures that the text across all your marketing channels looks the same.

With that out of the way, let’s look at how you can define and change the HTML font color.

When it comes to customizing your site, font color often gets overlooked… but it’s a simple edit that can add a lot of personality! ✨🎨Click to Tweet

Ways To Define Color

There are several ways to define color in web design, including name, RGB values, hex codes, and HSL values. Let’s take a look at how they work.

Color Name

Color names are the easiest way to define a color in your CSS styles. The color name refers to the specific name for the HTML color. Currently, there are 140 color names supported, and you can use any of those colors in your styles. For example, you can use “blue” to set the color for an individual element to blue.

HTML color names

HTML color names.

However, the downside of this approach is that not all color names are supported. In other words, if you use a color that’s not on the list of supported colors, you won’t be able to use it in your design by its color name.

RGB and RGBA Values

Next up, we have the RGB and RGBA values. The RGB stands for Red, Green, and Blue. It defines the color by mixing red, green, and blue values, similarly to how you’d mix a color on an actual palette.

RGB values

RGB values.

The RGB value looks like this: RGB(153,0,255). The first number specifies the red color input, the second specifies the green color input, and the third specifies blue.

The value of each color input can range between 0 and 255, where 0 means the color is not present at all and 255 means that the particular color is at its maximum intensity.

The RGBA value adds one more value to the mix, and that’s the alpha value that represents the opacity. It ranges from 0 (not transparent) to 1 (fully transparent).

HEX Value

HEX codes are another easy-to-use color selection option.

HEX codes are another easy-to-use color selection option.

The hex color codes work similarly to RGB codes. They consist of numbers from 0 to 9 and letters from A to F. The hex code looks like this: #800080. The first two letters specify the intensity of the red color, the middle two numbers specify the intensity of the green color, and the last two set the intensity of the blue color.

HSL and HSLA Values

Another way to define colors in HTML is to use HSL values. HSL stands for hue, saturation, and lightness.

HSL color values 

HSL color values.

Hue uses degrees from 0 to 360. On a standard color wheel, red is around 0/360, green is at 120, and blue is at 240.

Saturation uses percentages to define how saturated the color is. 0 represents black and white, and 100 represents the full color.

Lastly, lightness uses percentages similarly to saturation. In this case, 0% represents black, and 100% represents white.

For example, the purple color we’ve been using throughout this article would look like this in HSL: hsl(276, 100%, 50%).

HSL, like RGB, supports opacity. In that case, you’d use the HSLA value where A stands for alpha and is defined in a number from 0 to 1. if we wanted to lower the opacity of the example purple, we’d use this code: hsl(276, 100%, 50%, .85).

Now that you know how to define color, let’s look at different ways to change the HTML font color.

The Old: <font> Tags

Before HTML5 was introduced and set as the coding standard, you could change the font color using font tags. More specifically, you’d use the font tag with the color attribute to set the text color. The color was specified either with its name or with its hex code.

Here’s an example of how this code looked with hex color code:

<font color="#800080">This text is purple.</font>

And this is how you could set the text color to purple using the color name.

<font color="purple">This text is purple.</font> 

However, the <font> tag is deprecated in HTML5 and is no longer used. Changing the font color is a design decision, and design is not the primary purpose of HTML. Therefore, it makes sense that the <font> tags are no longer supported in HTML5.

So if the <font> tag is no longer supported, how do you change the HTML font color? The answer is with Cascading Style Sheets or CSS.

The New: CSS Styles

To change the HTML font color with CSS, you’ll use the CSS color property paired with the appropriate selector. CSS lets you use color names, RGB, hex, and HSL values to specify the color. There are three ways to use CSS to change the font color.

Inline CSS

Inline CSS is added directly to your HTML file. You’ll use the HTML tag such as <p> and then style it with the CSS color property like so:

<p style="color: purple">This is a purple paragraph.</p>

If you want to use a hex value, your code will look like this:

<p style="color:#800080">This is a purple paragraph.</p>

If you’re going to use the RGB value, you will write it like this:

<p style="color:RGB(153,0,255)">This is a purple paragraph.</p>

Lastly, using the HSL values, you’d use this code:

<p style="color:hsl(276, 100%, 50%)">This is a purple paragraph.</p>

The examples above show you how to change the color of a paragraph on your website. But you’re not limited to paragraphs alone. You can change the font color of your headings as well as links.

For example, replacing the <p> tag above with <h2> will change the color of that heading text, while replacing it with the <a> tag will change the color of that link. You can also use the <span> element to color any amount of text.

If you want to change the background color of the entire paragraph or a heading, it’s very similar to how you’d change the font color. You have to use the background-color attribute instead and use either the color name, hex, RGB, or HSL values to set the color. Here’s an example:  

<p style="background-color: purple">

Embedded CSS

Embedded CSS is within the <style> tags and placed in between the head tags of your HTML document.

The code will look like this if you want to use the color name:

<!DOCTYPE html>
<html>
<head>
  <style>
    <p> {
        color: purple;
    }
</style>
</head>

The code above will change the color of every paragraph on the page to purple. Similar to the inline CSS method, you can use different selectors to change the font color of your headings and links.

If you want to use the hex code, here’s how the code would look:

<!DOCTYPE html>
<html>
<head>
  <style>
    <p> {
        color: #800080;
    }
  </style>
</head>

The example below uses the RBGA values so you can see an example of setting the opacity:

<!DOCTYPE html>

<html>

<head>

<style>

<p> {

color: RGB(153,0,255,0.75),

}

</style>

</head>

And the HSL code would look like this:

<!DOCTYPE html>
<html>
<head>
  <style>
    <p> {
        color: hsl(276, 100%, 50%),
    }
  </style>
</head>

External CSS

Lastly, you can use external CSS to change the font color on your website. External CSS is CSS that’s placed in a separate stylesheet file, usually called style.css or stylesheet.css.

This stylesheet is responsible for all the styles on your site and specifies the font colors and font sizes, margins, paddings, font families, background colors, and more. In short, the stylesheet is responsible for how your site looks visually.

To change the font color with external CSS, you’d use selectors to style the parts of HTML you want. For example, this code will change all body text on your site:

body {color: purple;}

Remember, you can use RGB, hex, and HSL values and not just the color names to change the font color. If you want to edit the stylesheet, it’s recommended to do so in a code editor.

Inline, Embedded, or External?

So now you know how you can use CSS to change the font color. But which method should you use?

If you use the inline CSS code, you’ll add it directly into your HTML file. Generally speaking, this method is suitable for quick fixes. If you want to change the color of one specific paragraph or heading on a single page, this method is the fastest and the least complicated way to do it.

However, inline styles can make the size of your HTML file bigger. The bigger your HTML file is, the longer it will take for your webpage to load. In addition to that, inline CSS can make your HTML messy. As such, the inline method of using CSS to change the HTML font color is generally discouraged.

Embedded CSS is placed between the <head> tags and within the <style> tags. Like inline CSS, it’s good for quick fixes and overriding the styles specified in an external stylesheet.

One notable distinction between inline and embedded styles is that they will apply to any page that the head tags are loaded on, while inline styles apply only to the specific page they’re on, typically the element they’re targeting on that page.

The last method, external CSS, uses a dedicated stylesheet to define your visual styles. Generally speaking, it’s best to use an external stylesheet to keep all your styles in a single place, from where they are easy to edit. This also separates presentation and design, so the code is easy to manage and maintain.

Keep in mind that inline and embedded styles can override styles set in the external stylesheet.

Font Tags or CSS Styles: Pros and Cons

The two primary methods of changing the HTML font colors are to use the font tag or CSS styles. Both of these methods have their pros and cons.

HTML Font Tags Pros And Cons

The HTML font tag is easy to use, so that’s a pro in its favor. Typically speaking, CSS is more complicated and takes longer to learn than typing out <font color="purple">. If you have an older website that isn’t using HTML5, then the font tag is a viable method of changing the font color.

Even though the font tag is easy to use, you shouldn’t use it if your website uses HTML. As mentioned earlier, the font tag was deprecated in HTML5. Using deprecated code should be avoided as browsers could stop supporting it at any time. This can lead to your website breaking and not functioning correctly, or worse, not displaying at all for your visitors.

CSS Pros and Cons

CSS, like the font tag, has its pros and cons. The most significant advantage of using CSS is that it’s the proper way to change font color and specify all the other styles for your website.

As mentioned earlier, it separates presentation from design which makes your code easier to manage and maintain.

On the downside, CSS and HTML5 can take time to learn and write properly compared to the old way of writing code.

Keep in mind that with CSS, you have different ways of changing the font color, and each of those methods has its own set of pros and cons, as discussed earlier.

Tips for Changing HTML Font Color

Now that you know how to change the HTML font color, here are a few tips that will help you out.

Use A Color Picker

Color pickers streamline the color selection process.

Color pickers streamline the color selection process.

Instead of picking colors randomly, use color pickers to select the right colors. The benefit of a color picker is that it will give you the color name and the correct hex, RGB, and HSL values that you need to use in your code.

Check the Contrast

Use a contrast checker to test various text-to-background color contrast ratios.

Use a contrast checker to test various text-to-background color contrast ratios.

Dark text with dark background as well as light text with light background doesn’t work well together. They will make the text on your site hard to read. However, you can use a contrast checker to ensure your site’s colors are accessible and the text is easy to read.

Find the Color Using the Inspect Method

Using Inspect to find color codes.

Using Inspect to find color codes.

If you see a color that you like on a website, you can inspect the code to get the color’s hex, RGB, or HSL value. In Chrome, all you have to do is point your cursor to the part of the web page you want to inspect, right-click and select Inspect. This will open up the code inspection panel, where you can see a website’s HTML code and the corresponding styles.

Want to change the font color on your site? 🎨 It’s simple! This guide will help you get started ⬇️Click to Tweet

Summary

Changing the HTML font color can help improve your website’s readability and accessibility. It can also help you establish brand consistency in your website styles.

In this guide, you’ve learned about four different ways to change the HTML font color: with color names, hex codes, RGB, and HSL values.

We’ve also covered how you can change the font color with inline, embedded, and external CSS and use the font tag and the pros and cons of each method. By now, you should have a good understanding of which method you should use to change the HTML font color, so the only thing left to do now is to implement these tips on your site.

What are your thoughts on changing the font color with CSS and font tag? Let us know in the comments section!


Get all your applications, databases and WordPress sites online and under one roof. Our feature-packed, high-performance cloud platform includes:

  • Easy setup and management in the MyKinsta dashboard
  • 24/7 expert support
  • The best Google Cloud Platform hardware and network, powered by Kubernetes for maximum scalability
  • An enterprise-level Cloudflare integration for speed and security
  • Global audience reach with up to 35 data centers and 275 PoPs worldwide

Test it yourself with $20 off your first month of Application Hosting or Database Hosting. Explore our plans or talk to sales to find your best fit.

Раздел:
Сайтостроение /
HTML /

План заработка в Интернете

План заработка в Интернете

Как правильно выбрать партнерские программы, чтобы гарантированно зарабатывать? Что необходимо сделать вначале, чтобы ваш заработок был стабильным и предсказуемым? Возможно ли стартовать вообще без денег и каких-либо вложений в рекламу? Этот план поможет вам сделать первые шаги к заработку, даст ответы на важные вопросы и убережет от ошибок в начале пути.
Подробнее…

Изменение цвета текста в HTML выполняется довольно просто (впрочем, как и почти все остальные действия с HTML). Но, прежде чем рассказать об этом, я немного пройдусь по вопросу безопасных цветов…

Что такое безопасный цвет HTML

Постараюсь быть кратким. Суть в том, что современные компьютеры для кодирования цвета используют довольно большие числа. И, соответственно, в этих больших числах можно закодировать очень большое количество оттенков. Но беда в том, что многие видеокарты и мониторы не могут правильно отобразить ВСЕ эти оттенки. Поэтому, например, цвет, код которого FFFFAA, на вашем мониторе может выглядеть иначе, чем на мониторе другого пользователя. Также декодирование цветов может отличаться в зависимости от операционной системы пользователя (Windows может декодировать цвет не так, как, например, Mac).

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

Существует таблица безопасных цветов, в которой перечислены эти цвета. Именно этот набор цветов желательно использовать при создании веб-страниц.

Надо сказать, что в наше время это уже не так значимо, поскольку почти у всех современные
мониторы, видеокарты и браузеры. Поэтому, конечно, вы можете использовать и другие цвета, “НЕ безопасные”. Однако без особой надобности этого всё-таки лучше не делать, и работать по возможности с безопасными цветами.

Как поменять цвет текста в HTML

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

А здесь я расскажу только об одном старом добром способе, который использует
тег цвета текста
в HTML — тег <font> (точнее, этот тег может изменять не только цвет, но об этом как-нибудь в другой раз).

С одной стороны, этот тег признан нежелательным стандартами HTML4 и XHTML. Но с другой стороны, он поддерживается всеми браузерами, в том числе и устаревшими.

Это парный тег (то есть наличие закрывающего тега обязательно). С помощью этого тега можно установить шрифт, его размер и цвет. Но мы пока будем говорить только о цвете.

Тег <font> может иметь несколько разных атрибутов. Для изменения цвета используется
атрибут color.

Значение этого атрибута может быть введено одним из двух способов:

  • Как определение красного, зелёного и синего (RGB).
  • Как стандартное название цвета.

Пример:

Следующий текст будет <font color="red">красным</font>.

Следующий текст будет тоже <font color="#FF0000">красным</font>.

Значение атрибута лучше заключать в кавычки (хотя это и необязательно).

Цветовая модель RGB

В цветовой модели RGB обозначение цвета представляет собой шестизначное
шестнадцатеричное число. Для обозначения кода цвета в HTML перед этим числом должен быть знак решётки (#).

Первые две цифры определяют насыщенность красного цвета (от 00 — нет красного, до FF — ярко-красный. Таким же образом определяется насыщенность для зелёного (следующие две цифры) и синего (последние две цифры). Таким образом формат числа, с помощью которого кодируется цвет, следующий:

#RRGGBB

Где RR — красная составляющая, GG — зелёная, BB — синяя.

Чёрный цвет — это отсутствие “свечения” всех составляющих — #000000, а белый цвет — это наибольшая насыщенность RGB — #FFFFFF.

Также можно использовать сокращённую запись, когда вместо двух цифр используется одна:

Следующий текст будет тоже <font color="#F00">красным</font>.

В этом случае формат записи числа будет таким:

#RGB

ВНИМАНИЕ!
Некоторые бразуеры не поддерживают такой формат записи цветового кода.

Названия цветов HTML

Как уже было сказано, вместо числового кода для обозначения цвета можно использовать название цвета. Во многих случаях это более удобно и более понятно.

В стандартах HTML4 и XHTML определены следующие названия цветов (в скобках указаны RGB-коды):

aqua    (#00FFFF)     gray   (#808080)   
navy    (#000080)     silver (#C0C0C0)   
black   (#FFFFFF)     green  (#008000)
olive   (#808000)     teal   (#008080)   
blue    (#0000FF)     lime   (#00FF00)   
purple  (#800080)     yellow (#FFFF00)
fuchsia (#FF00FF)     maroon (#800000)   
red     (#FF0000)     white  (#FFFFFF)

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

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

Как создать свой сайт

Как создать свой сайт

Очень небольшая книга, которую можно прочитать буквально за 15 минут. Но эти 15 минут дадут вам представление о том, как создаются современные сайты…
Подробнее…

Помощь в технических вопросах

Помощь в технических вопросах

Помощь студентам. Курсовые, дипломы, чертежи (КОМПАС), задачи по программированию: Pascal/Delphi/Lazarus; С/С++; Ассемблер; языки программирования ПЛК; JavaScript; VBScript; Fortran; Python; C# и др. Разработка (доработка) ПО ПЛК (предпочтение — ОВЕН, CoDeSys 2 и 3), а также программирование панелей оператора, программируемых реле и других приборов систем автоматизации.
Подробнее…

Понравилась статья? Поделить с друзьями:
  • Яндекс браузер вкладки снизу как исправить
  • Яндекс браузер runtime error
  • Ядро недостаточно памяти heroes of the storm как исправить
  • Яндекс браузер net err cert authority invalid как исправить на виндовс 7
  • Ягодичный мостик ошибки при выполнении