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

I have the below message (slightly changed): "Enter the competition by January 30, 2011 and you could win up to $$$$ — including amazing summer trips!" I currently have: <p style="font-size:

I have the below message (slightly changed):

«Enter the competition by January 30, 2011 and you could win up to
$$$$ — including amazing summer trips!»

I currently have:

<p style="font-size:14px; color:#538b01; font-weight:bold; font-style:italic;">

formatting the text string, but want to change the color of «January 30, 2011» to #FF0000 and «summer» to #0000A0.

How do I do this strictly with HTML or inline CSS?

Sam R.'s user avatar

Sam R.

15.9k11 gold badges68 silver badges121 bronze badges

asked Jan 7, 2011 at 5:38

Mitch's user avatar

<p style="font-size:14px; color:#538b01; font-weight:bold; font-style:italic;">
  Enter the competition by 
  <span style="color: #ff0000">January 30, 2011</span>
  and you could win up to $$$$ — including amazing 
  <span style="color: #0000a0">summer</span> 
  trips!
</p>

Or you may want to use CSS classes instead:

<html>
  <head>
    <style type="text/css">
      p { 
        font-size:14px; 
        color:#538b01; 
        font-weight:bold; 
        font-style:italic;
      }
      .date {
        color: #ff0000;
      }
      .season { /* OK, a bit contrived... */
        color: #0000a0;
      }
    </style>
  </head>
  <body>
    <p>
      Enter the competition by 
      <span class="date">January 30, 2011</span>
      and you could win up to $$$$ — including amazing 
      <span class="season">summer</span> 
      trips!
    </p>
  </body>
</html>

answered Jan 7, 2011 at 5:41

Jacob's user avatar

JacobJacob

76.8k24 gold badges147 silver badges228 bronze badges

3

You could use the HTML5 Tag <mark>:

<p>Enter the competition by 
<mark class="red">January 30, 2011</mark> and you could win up to $$$$ — including amazing 
<mark class="blue">summer</mark> trips!</p>

And use this in the CSS:

p {
    font-size:14px;
    color:#538b01;
    font-weight:bold;
    font-style:italic;
}

mark.red {
    color:#ff0000;
    background: none;
}

mark.blue {
    color:#0000A0;
    background: none;
}

The tag <mark> has a default background color… at least in Chrome.

bad_coder's user avatar

bad_coder

10.4k20 gold badges43 silver badges65 bronze badges

answered Dec 14, 2012 at 23:58

Juan Pablo Pinedo's user avatar

4

<p style="font-size:14px; color:#538b01; font-weight:bold; font-style:italic;">
    Enter the competition by <span style="color:#FF0000">January 30, 2011</span> and you could win up to $$$$ — including amazing <span style="color:#0000A0">summer</span> trips!
</p>

The span elements are inline an thus don’t break the flow of the paragraph, only style in between the tags.

answered Jan 7, 2011 at 5:41

Damien-Wright's user avatar

Damien-WrightDamien-Wright

7,1364 gold badges27 silver badges23 bronze badges

use spans. ex) <span style='color: #FF0000;'>January 30, 2011</span>

answered Jan 7, 2011 at 5:41

brian_d's user avatar

brian_dbrian_d

11.1k4 gold badges47 silver badges72 bronze badges

<font color="red">This is some text!</font> 

This worked the best for me when I only wanted to change one word into the color red in a sentence.

Josh Lee's user avatar

Josh Lee

167k37 gold badges268 silver badges273 bronze badges

answered Sep 10, 2017 at 15:01

user8588011's user avatar

user8588011user8588011

2833 silver badges2 bronze badges

3

You can also make a class:

<span class="mychangecolor"> I am in yellow color!!!!!!</span>

then in a css file do:

.mychangecolor{ color:#ff5 /* it changes to yellow */ }

Muds's user avatar

Muds

3,9545 gold badges32 silver badges51 bronze badges

answered Nov 20, 2015 at 15:34

JayMcpeZ_'s user avatar

JayMcpeZ_JayMcpeZ_

511 silver badge1 bronze badge

Tailor this code however you like to fit your needs, you can select text? in the paragraph to be what font or style you need!:

<head>
<style>
p{ color:#ff0000;font-family: "Times New Roman", Times, serif;} 
font{color:#000fff;background:#000000;font-size:225%;}
b{color:green;}
</style>
</head>
<body>
<p>This is your <b>text. <font>Type</font></strong></b>what you like</p>
</body>

Wtower's user avatar

Wtower

18.2k11 gold badges106 silver badges78 bronze badges

answered Jun 19, 2016 at 11:23

Trevor Lee's user avatar

You could use the longer boringer way

<p style="font-size:14px; color:#538b01; font-weight:bold; font-style:italic;">Enter the competition by</p><p style="font-size:14px; color:#ff00; font-weight:bold; font-style:italic;">summer</p> 

you get the point for the rest

answered Nov 17, 2015 at 19:51

otis answer's user avatar

I have the below message (slightly changed):

«Enter the competition by January 30, 2011 and you could win up to
$$$$ — including amazing summer trips!»

I currently have:

<p style="font-size:14px; color:#538b01; font-weight:bold; font-style:italic;">

formatting the text string, but want to change the color of «January 30, 2011» to #FF0000 and «summer» to #0000A0.

How do I do this strictly with HTML or inline CSS?

Sam R.'s user avatar

Sam R.

15.9k11 gold badges68 silver badges121 bronze badges

asked Jan 7, 2011 at 5:38

Mitch's user avatar

<p style="font-size:14px; color:#538b01; font-weight:bold; font-style:italic;">
  Enter the competition by 
  <span style="color: #ff0000">January 30, 2011</span>
  and you could win up to $$$$ — including amazing 
  <span style="color: #0000a0">summer</span> 
  trips!
</p>

Or you may want to use CSS classes instead:

<html>
  <head>
    <style type="text/css">
      p { 
        font-size:14px; 
        color:#538b01; 
        font-weight:bold; 
        font-style:italic;
      }
      .date {
        color: #ff0000;
      }
      .season { /* OK, a bit contrived... */
        color: #0000a0;
      }
    </style>
  </head>
  <body>
    <p>
      Enter the competition by 
      <span class="date">January 30, 2011</span>
      and you could win up to $$$$ — including amazing 
      <span class="season">summer</span> 
      trips!
    </p>
  </body>
</html>

answered Jan 7, 2011 at 5:41

Jacob's user avatar

JacobJacob

76.8k24 gold badges147 silver badges228 bronze badges

3

You could use the HTML5 Tag <mark>:

<p>Enter the competition by 
<mark class="red">January 30, 2011</mark> and you could win up to $$$$ — including amazing 
<mark class="blue">summer</mark> trips!</p>

And use this in the CSS:

p {
    font-size:14px;
    color:#538b01;
    font-weight:bold;
    font-style:italic;
}

mark.red {
    color:#ff0000;
    background: none;
}

mark.blue {
    color:#0000A0;
    background: none;
}

The tag <mark> has a default background color… at least in Chrome.

bad_coder's user avatar

bad_coder

10.4k20 gold badges43 silver badges65 bronze badges

answered Dec 14, 2012 at 23:58

Juan Pablo Pinedo's user avatar

4

<p style="font-size:14px; color:#538b01; font-weight:bold; font-style:italic;">
    Enter the competition by <span style="color:#FF0000">January 30, 2011</span> and you could win up to $$$$ — including amazing <span style="color:#0000A0">summer</span> trips!
</p>

The span elements are inline an thus don’t break the flow of the paragraph, only style in between the tags.

answered Jan 7, 2011 at 5:41

Damien-Wright's user avatar

Damien-WrightDamien-Wright

7,1364 gold badges27 silver badges23 bronze badges

use spans. ex) <span style='color: #FF0000;'>January 30, 2011</span>

answered Jan 7, 2011 at 5:41

brian_d's user avatar

brian_dbrian_d

11.1k4 gold badges47 silver badges72 bronze badges

<font color="red">This is some text!</font> 

This worked the best for me when I only wanted to change one word into the color red in a sentence.

Josh Lee's user avatar

Josh Lee

167k37 gold badges268 silver badges273 bronze badges

answered Sep 10, 2017 at 15:01

user8588011's user avatar

user8588011user8588011

2833 silver badges2 bronze badges

3

You can also make a class:

<span class="mychangecolor"> I am in yellow color!!!!!!</span>

then in a css file do:

.mychangecolor{ color:#ff5 /* it changes to yellow */ }

Muds's user avatar

Muds

3,9545 gold badges32 silver badges51 bronze badges

answered Nov 20, 2015 at 15:34

JayMcpeZ_'s user avatar

JayMcpeZ_JayMcpeZ_

511 silver badge1 bronze badge

Tailor this code however you like to fit your needs, you can select text? in the paragraph to be what font or style you need!:

<head>
<style>
p{ color:#ff0000;font-family: "Times New Roman", Times, serif;} 
font{color:#000fff;background:#000000;font-size:225%;}
b{color:green;}
</style>
</head>
<body>
<p>This is your <b>text. <font>Type</font></strong></b>what you like</p>
</body>

Wtower's user avatar

Wtower

18.2k11 gold badges106 silver badges78 bronze badges

answered Jun 19, 2016 at 11:23

Trevor Lee's user avatar

You could use the longer boringer way

<p style="font-size:14px; color:#538b01; font-weight:bold; font-style:italic;">Enter the competition by</p><p style="font-size:14px; color:#ff00; font-weight:bold; font-style:italic;">summer</p> 

you get the point for the rest

answered Nov 17, 2015 at 19:51

otis answer's user avatar

I’m designing a web site and i would like to ask you guys that, how can I change the color of just one character in a string in a text box of HTML by CSS?

example : STACK OVER FLOW just the ‘A’ letter is red!

bad_coder's user avatar

bad_coder

10.4k20 gold badges43 silver badges65 bronze badges

asked Jun 27, 2013 at 11:16

bluewonder's user avatar

1

You can’t do this with a regular <input type="text"> or <textarea> element, but with a normal element (like <div> or <p>) made contenteditable, you have all the freedoms of html/css formatting.

<div contenteditable>
    ST<span style="color: red">A</span>CK OVERFLOW
</div>

http://jsfiddle.net/jVqDJ/

The browser support is very good as well (IE5.5+). Read more at https://developer.mozilla.org/en-US/docs/Web/HTML/Content_Editable

answered Jun 27, 2013 at 11:20

xec's user avatar

xecxec

17k3 gold badges44 silver badges53 bronze badges

2

I can’t believe no one has suggested this yet. But if you’re ok with a WebKit only solution, you can make a color gradient with discrete separations and apply it to the text like this:

.c1 {
  background: linear-gradient(to right, black 0% 1.19em, red 1.19em 1.9em, black 1.9em 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
}

.c2 {
  color: white;
  background: linear-gradient(to right, black 0% 1.19em, red 1.19em 1.9em, black 1.9em 100%);
  
}

input{
  font-family: "Courier New", Courier;
}

.c3 {
  background: linear-gradient(to right, black 0% 1.4em, red 1.2em 1.95em, black 1.95em 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
}
<h1 class="c1">
STACK OVER FLOW
</h1>
This is what the gradient looks like with the text over it:
<h1 class="c2">
STACK OVER FLOW
</h1>
It even works on input forms, however you'll want to change the font to a Monospaced font like Courier so the color always lines up with the same letter:
<h1>
<input type="text" class="c3"></input>
</h1>

This is nice because it’s not limited by the tag the text is placed in like some of the other answers. And if you’re in a situation where you can’t really change the html (for instance if you’re using the same style sheet on multiple pages and need to make a retroactive change) this could be helpful. If you can change the html though, xec’s answer has much better browser support.

answered Oct 13, 2020 at 8:16

Partial Science's user avatar

3

I just want to add to the solution if you want to change color of only first character then there is a CSS selector element::first-letter

example:

div::first-letter{
   color: red;
}

answered Mar 16, 2020 at 9:48

Sumit's user avatar

SumitSumit

1782 silver badges9 bronze badges

It is not possible in input but you can change the background color to red if it is not in range using CSS only.

Input number less than 0 or greater than 1000

input:out-of-range {
  background-color: red;
}
<input type="number" min="0" max="1000" />

answered Jul 14, 2021 at 12:38

DecPK's user avatar

DecPKDecPK

23.7k6 gold badges23 silver badges41 bronze badges

You could try using

<style> 
span.green{ 
     color:green; 
    } 
span.purple{ 
       color:purple; 
    } 
</style> 

<spanclass="purple">Var</span> x = "<span class="green">dude</span>"; 

answered Feb 28, 2020 at 13:18

NeoEmberArts's user avatar

From css you can only change an elements property so you need to insert the letter «A» in another element like this:

ST<span>A</span>CK OVER FLOW just the 'A' letter is red!

And the CSS part is

span{
   color:#FF0000;
}

Or attach a class to it like this

ST<span class="myRedA">A</span>CK OVER FLOW just the '<A' letter is red!

CSS:

span.myRedA{
       color:#FF0000;
    }

answered Jun 27, 2013 at 11:23

eblue's user avatar

eblueeblue

991 gold badge3 silver badges12 bronze badges

0

you could use bold tags A

css:

b {
font-color: red;
}

answered Jan 9, 2018 at 18:49

Endgamers's user avatar

<font color="#colors">text text text</font> 

Alex Celeste's user avatar

Alex Celeste

12.6k10 gold badges50 silver badges88 bronze badges

answered Oct 18, 2014 at 18:53

Pixie Lumis Serigala's user avatar


Загрузить 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 раз.

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


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,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. 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,980,696 times.

Is this article up to date?

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

Понравилась статья? Поделить с друзьями:

Читайте также:

  • Как изменить цвет часов на экране телефона самсунг
  • Как изменить цвет часов на экране блокировки хонор
  • Как изменить цвет часов на экране блокировки самсунг а51
  • Как изменить цвет часов на экране блокировки самсунг а50
  • Как изменить цвет часов на экране блокировки самсунг а22

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии