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.
15.9k11 gold badges68 silver badges121 bronze badges
asked Jan 7, 2011 at 5:38
<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
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
10.4k20 gold badges43 silver badges65 bronze badges
answered Dec 14, 2012 at 23:58
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-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_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
167k37 gold badges268 silver badges273 bronze badges
answered Sep 10, 2017 at 15:01
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
3,9545 gold badges32 silver badges51 bronze badges
answered Nov 20, 2015 at 15:34
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
18.2k11 gold badges106 silver badges78 bronze badges
answered Jun 19, 2016 at 11:23
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
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.
15.9k11 gold badges68 silver badges121 bronze badges
asked Jan 7, 2011 at 5:38
<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
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
10.4k20 gold badges43 silver badges65 bronze badges
answered Dec 14, 2012 at 23:58
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-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_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
167k37 gold badges268 silver badges273 bronze badges
answered Sep 10, 2017 at 15:01
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
3,9545 gold badges32 silver badges51 bronze badges
answered Nov 20, 2015 at 15:34
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
18.2k11 gold badges106 silver badges78 bronze badges
answered Jun 19, 2016 at 11:23
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
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
10.4k20 gold badges43 silver badges65 bronze badges
asked Jun 27, 2013 at 11:16
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
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
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
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
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
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
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
<font color="#colors">text text text</font>
Alex Celeste
12.6k10 gold badges50 silver badges88 bronze badges
answered Oct 18, 2014 at 18:53
Здравствуйте, дороге друзья!
При оформлении текста на сайте нам часто приходится изменять цвет текста, размер, жирность, начертание и так далее. В этой статье вы узнаете как в HTML изменить цвет текста не прибегая к помощи дополнительных плагинов, модулей и библиотек.
Навигация по статье:
- Изменения цвета текста средствами HTML
- Как изменить цвет текста в HTML с использованием CSS?
- Изменяем цвет в HTML коде при помощи атрибута style
- Что делать если внесённые изменения не меняются?
Если ваш сайт сделан на одной из CMS, то для изменения цвета текста вы можете использовать встроенный функционал визуального редактора, однако такая функция там не всегда есть, а ставить ради этого дополнительный модуль или плагин не всегда есть смысл.
Плюс бывают ситуации когда вам нужно изменить цвет текста в виджете или слайдере или ещё где то, где визуальный редактор не поддерживается.

К счастью в HTML есть специальный тег с атрибутом color, в котором можно указать нужный цвет текста.
|
<font color=«red»>Красный текст</font> |
Значение цвета можно задавать несколькими способами:
- При помощи кодового названия (Например: red, black, blue)
- В шестнадцатиричном формате (Например: #000000, #ccc)
- В формате rgba (Например: rgba(0,0,0,0.5))
Если вы ещё не знаете как определить значение цвета на сайте, то вам сюда
Таким образом вы можете изменить цвет у целого абзаца, слова или одной буквы, обернув то что вам нужно в тег <font>
Как изменить цвет текста в HTML с использованием CSS?
Для изменения цвета текста для определённого абзаца или слова можно присвоить ему класс, а затем в CSS файле задать для этого класса свойство color.
Выглядеть это будет так:
HTML
|
<p class=”color—text”>Пример текста</div> |
CSS
|
.color—text { color:#555555; } |
Вместо color-text вы можете указать свой класс.
Если вам нужно изменить цвет текста для элемента на сайте у которого уже есть класс или идентификатор, то можно вычислить его название и указать в CSS.
Если вы не хотите лезть в CSS файл чтобы внести изменения, то можно дописать CSS стили прямо в HTML коде станицы, воспользовавшись тегом <style>.
Для этого:
- 1.Находи вверху HTML страницы тег </head>. Если ваш сайт работает на CMS, то этот фрагмент кода находится в одном из файлов шаблона. Например: header.php, head.php или что-то наподобие этого в зависимости от CMS.
- 2.Перед строкой </head> добавляем теги <style>…</style>.
- 3.Внутри этих тегов задаём те CSS свойства, которые нам нужны. В данном случае color:
<style>
.color-text {
color:#555555;
}
</style>
Этот способ подходит если вам нужно изменить цвет сразу для нескольких элементов на сайте.
Если же такой элемент один, то можно задать или изменить цвет текста прямо в HTML коде.
Изменяем цвет в HTML коде при помощи атрибута style
Для этого добавляем к тегу для которого нам нужно изменить цвет текста атрибут style.
|
<p style=”color:red;”>Пример</p> |
Здесь же при необходимости через ; вы можете задать и другие CSS свойства, например, размер шрифта, жирность и так далее.
|
<p style=”color:red; font—size:20px; font—weight:bolder;”>Пример</p> |
Лично я обычно использую вариант с заданием стилей в CSS файле, но если вам нужно изменить цвет текста для какого то одного-двух элементов, то не обязательно присваивать им класс и потом открывать CSS файл и там дописывать слили. Проще это сделать прямо в HTML при помощи тега <font> или артибута style.
Так же вы должны знать, что есть такое понятие как приоритет стилей. Так вот когда вы задаёте цвет текста или другие стили в html при помощи атрибута style, то у этих стилей приоритет будет выше чем если вы их зададите в CSS файле (при условии что там не использовалось правило !important)
Чтобы изменить цвет текста отдельного слова, фразы или буквы мы можем обернуть их в тег span и задать ему нужный цвет.
Например:
|
<p>Пример <span style=”color:#2F73B6;”> текста</span></p> |
В итог получится вот так:
Пример текста
Что делать если внесённые изменения не меняются?
Казалось бы, изменение цвета – одна из простейших операций при оформлении текста, ну что здесь может пойти не так?
Однако и здесь есть свои нюансы, которые нужно учитывать:
- 1.Приоритет стилей, о котором я писала выше. Если задавать цвет текста прямо в HTML то приоритет будет выше. Если вы задали его при помощи атрибута style, а он всё равно не изменилcя, то попробуйте добавить к нему правило !important;
<p style=”color:#fff!important;”>…</p>
- 2.Особенности тегов. Если вы зададите цвет текста для абзаца внутри которого есть ссылка, то он изменится для всего абзаца кроме ссылки. Чтобы изменился цвет ссылки нужно задавать его именно для тега ссылки.
Аналогично если вы зададите цвет текста для блока, внутри которого находится список, то для элементов этого списка он может не примениться и нужно будет отдельно задавать его именно для тегов списка.
- 3.Кеширование. Часто современные браузеры кешируют стили сайта и даже после внесения изменений в код они ещё какое то время отображают старую версию стилей. Для решения проблемы можно обновлять страницу при помощи сочетания клавиш CTRL+F5.
Так же у вас на сайте может стоять плагин для кеширования, из-за которого вы так же можете не видеть внесённых изменений на сайте.

Вот, в общем то и всё что касается изменения цвета в HTML. Как видите, ничего сложного! Если у вас возникнут какие то вопросы – пишите их в комментариях.
Успехов вам и вашим проектам!
С уважением Юлия Гусарь
Download Article
Easily change the color of text using CSS or HTML
Download Article
- Creating Text Styles
- Using Inline Styles
- Q&A
- Tips
|
|
|
Do you want to change the color of the text on a web page? In HTML5, you can use CSS to define what color the text will appear in various elements on your page. You can also use inline style attributes to change the color of individual text elements in your CSS file. Using CSS will ensure that your web page is compatible with every possible browser. You can also use external CSS files to create a standard font color for a specific style across your entire website. This wikiHow article teaches you how to change text color using HTML and CSS.
-
1
Open your HTML file. The best way to change the color of your text is by using CSS. The old HTML <font> attribute is no longer supported in HTML5. The preferred method is to use CSS to define the style of your elements. Go ahead and open or create a new HTML document.
- This method will also work with separate CSS files that are linked to your HTML document. The examples used in this article are for an HTML file using an internal stylesheet.
-
2
Place your cursor inside the head of your HTML file. When you are using an internal style sheet for a specific HTML file, it is usually placed within the head of the HTML file. The head is at the top of the sheet in between the opening <head> tag, and the closing </head> tag.
- If your HTML document does not have a head, go ahead and enter the opening and closing head tags at the top of your HTML file.
Advertisement
-
3
Type the opening and closing tags for the style sheet. All CSS elements that affect the style of the webpage go in between the opening and closing style tags within the head section of your HTML document. Type <style> in the «head» section to create the opening style tag. Then type </style> a couple of lines down to create the closing style tag. When you’re finished, the beginning of your HTML file should look something like this:[1]
<!DOCTYPE html> <html> <head> <style> </style> </head>
-
4
Type the element you want to change the text color for followed by the opening and closing brackets. Elements you can change include the text body (body), paragraph text («<p>»), as well as headers («<h1>», «<h2>», «<h3>», etc.). Then enter the opening bracket («{«) one space after. Then add the closing bracket («}») a few lines down. In this example, we will be changing the «body» text. The beginning of your HTML file should look something like the following:
<!DOCTYPE html> <html> <head> <style> body { } </style> </head>
-
5
Add the color attribute into the element section of the CSS. Type color: in between the opening and closing brackets of the text element you just created. The «color:» attribute will tell the page what text color to use for that element. So far, the head of your HTML file should look something like the following:
<!DOCTYPE html> <html> <head> <style> body { color: } </style> </head>
-
6
Type in a color for the text followed by a semi-colon («;»). There are three ways you can enter a color: the name, the hex value, or the RGB value. For example, for the color blue you could type blue; for the color name, rgb(0, 0, 255); for the RGB value, or #0000FF; for the hex value. Your HTML page should look something like the following:
<!DOCTYPE html> <html> <head> <style> body { color: red; } </style> </head>
-
7
Add other selectors to change the color of various elements. You can use different selectors to change the color of different text elements. If you want the header to be a different color than the paragraph text or body text, you will need to create a different selector for each element within the «<style>» section. In the following example, we change the color of the body text to red, the header text to green, and the paragraph text to blue:
<!DOCTYPE html> <html> <head> <style> body { color: red; } h1 { color: #00FF00; } p { color: rgb(0,0,255) } </style> </head> <body> <h1>This header will be green.</h1> <p>This paragraph will be blue.</p> This body text will be red. </body> </html>
-
8
Define a CSS class that changes text color. In CSS, you can define a class rather than using the existing elements. You can apply the class to any text element within your HTML document. To do so, type a period («.») followed by the name of the class you’d like to define. In the following example, we define a new class called «.redtext», which changes the color of the text to red. Then we apply it to the header at the top of the HTML document. Checkout the following example:
<!DOCTYPE html> <html> <head> <style> .redtext { color: red; } </style> </head> <body> <h1 class="redtext">This heading will be red</h1> <p>This paragraph will be normal.</p> <p class="redtext">This paragraph will be red</p> </body> </html>
Advertisement
-
1
Open your HTML file. You can use inline HTML style attributes to change the style of a single element on your page. This can be useful for one or two quick changes to the style but is not recommended for widespread use. It’s best to use CSS for comprehensive changes. Go ahead and open or create a new HTML document.[2]
-
2
Find the text element in the file that you want to change. You can use inline style attributes to change the text color of any of your text elements, including paragraph text («<p>»»), or your headline text («<h1>»).
<!DOCTYPE html> <html> <body> <h1>This is the header you want to change</h1> </body> </html>
-
3
Add the style attribute to the element. To do so, Type style="" inside the opening tag for the element you want to change. In the following example, we have added the style attribute to the header text:
<!DOCTYPE html> <html> <body> <h1 style="">This is the header you want to change</h1> </body> </html>
-
4
Type the color: attribute inside the quotation marks. Type «color» with a colon («:») within the quotation marks after the style attribute. So far, your HTML file should look something like the following:
<!DOCTYPE html> <html> <body> <h1 style="color:">This is the header you want to change</h1> </body> </html>
-
5
Type the color you want to change the text to followed by a semi-colon («;»). There are three ways you can express a color. You can type the name of the color, you can enter the RGB value, or you can enter the hex value. For example, to change the color to yellow, you could type yellow; for the color name, rgb(255,255,0); for the RGB value, or #FFFF00; to use the hex value. In the following example, we change the headline color to yellow using the hex value:
<!DOCTYPE html> <html> <body> <h1 style="color:#FFFF00;">This header is now yellow</h1> </body> </html>
Advertisement
Add New Question
-
Question
How would I type bold font in html?
<b></b> is the code for bold text, so you would put your text within that, e.g. <b> hello world </b>.
-
Question
How do I change background colors in HTML?
Use the bgcolor attribute with body tag.
-
Question
How do I change the color of the background?
You will create a similar tag as you did to change the font color. After putting everything in the body tag, you will put the {} brackets and on the inside, type «background-color:(insert desired color).» In code, it should look like this:
body {
color: black;
background-color:gold
}This code gives you black text and a gold background.
See more answers
Ask a Question
200 characters left
Include your email address to get a message when this question is answered.
Submit
Advertisement
-
You can see a list of supported color names and their hex values at http://www.w3schools.com/colors/colors_names.asp
Thanks for submitting a tip for review!
Advertisement
About This Article
Article SummaryX
1. Open the file in a text editor.
2. Find the element you want to change.
3. Type style=″color:#FFFF00;″ in the opening tag.
4. Replace ″#FFFF00″ with your desired color.
Did this summary help you?
Thanks to all authors for creating a page that has been read 1,980,696 times.
Is this article up to date?
Download Article
Easily change the color of text using CSS or HTML
Download Article
- Creating Text Styles
- Using Inline Styles
- Q&A
- Tips
|
|
|
Do you want to change the color of the text on a web page? In HTML5, you can use CSS to define what color the text will appear in various elements on your page. You can also use inline style attributes to change the color of individual text elements in your CSS file. Using CSS will ensure that your web page is compatible with every possible browser. You can also use external CSS files to create a standard font color for a specific style across your entire website. This wikiHow article teaches you how to change text color using HTML and CSS.
-
1
Open your HTML file. The best way to change the color of your text is by using CSS. The old HTML <font> attribute is no longer supported in HTML5. The preferred method is to use CSS to define the style of your elements. Go ahead and open or create a new HTML document.
- This method will also work with separate CSS files that are linked to your HTML document. The examples used in this article are for an HTML file using an internal stylesheet.
-
2
Place your cursor inside the head of your HTML file. When you are using an internal style sheet for a specific HTML file, it is usually placed within the head of the HTML file. The head is at the top of the sheet in between the opening <head> tag, and the closing </head> tag.
- If your HTML document does not have a head, go ahead and enter the opening and closing head tags at the top of your HTML file.
Advertisement
-
3
Type the opening and closing tags for the style sheet. All CSS elements that affect the style of the webpage go in between the opening and closing style tags within the head section of your HTML document. Type <style> in the «head» section to create the opening style tag. Then type </style> a couple of lines down to create the closing style tag. When you’re finished, the beginning of your HTML file should look something like this:[1]
<!DOCTYPE html> <html> <head> <style> </style> </head>
-
4
Type the element you want to change the text color for followed by the opening and closing brackets. Elements you can change include the text body (body), paragraph text («<p>»), as well as headers («<h1>», «<h2>», «<h3>», etc.). Then enter the opening bracket («{«) one space after. Then add the closing bracket («}») a few lines down. In this example, we will be changing the «body» text. The beginning of your HTML file should look something like the following:
<!DOCTYPE html> <html> <head> <style> body { } </style> </head>
-
5
Add the color attribute into the element section of the CSS. Type color: in between the opening and closing brackets of the text element you just created. The «color:» attribute will tell the page what text color to use for that element. So far, the head of your HTML file should look something like the following:
<!DOCTYPE html> <html> <head> <style> body { color: } </style> </head>
-
6
Type in a color for the text followed by a semi-colon («;»). There are three ways you can enter a color: the name, the hex value, or the RGB value. For example, for the color blue you could type blue; for the color name, rgb(0, 0, 255); for the RGB value, or #0000FF; for the hex value. Your HTML page should look something like the following:
<!DOCTYPE html> <html> <head> <style> body { color: red; } </style> </head>
-
7
Add other selectors to change the color of various elements. You can use different selectors to change the color of different text elements. If you want the header to be a different color than the paragraph text or body text, you will need to create a different selector for each element within the «<style>» section. In the following example, we change the color of the body text to red, the header text to green, and the paragraph text to blue:
<!DOCTYPE html> <html> <head> <style> body { color: red; } h1 { color: #00FF00; } p { color: rgb(0,0,255) } </style> </head> <body> <h1>This header will be green.</h1> <p>This paragraph will be blue.</p> This body text will be red. </body> </html>
-
8
Define a CSS class that changes text color. In CSS, you can define a class rather than using the existing elements. You can apply the class to any text element within your HTML document. To do so, type a period («.») followed by the name of the class you’d like to define. In the following example, we define a new class called «.redtext», which changes the color of the text to red. Then we apply it to the header at the top of the HTML document. Checkout the following example:
<!DOCTYPE html> <html> <head> <style> .redtext { color: red; } </style> </head> <body> <h1 class="redtext">This heading will be red</h1> <p>This paragraph will be normal.</p> <p class="redtext">This paragraph will be red</p> </body> </html>
Advertisement
-
1
Open your HTML file. You can use inline HTML style attributes to change the style of a single element on your page. This can be useful for one or two quick changes to the style but is not recommended for widespread use. It’s best to use CSS for comprehensive changes. Go ahead and open or create a new HTML document.[2]
-
2
Find the text element in the file that you want to change. You can use inline style attributes to change the text color of any of your text elements, including paragraph text («<p>»»), or your headline text («<h1>»).
<!DOCTYPE html> <html> <body> <h1>This is the header you want to change</h1> </body> </html>
-
3
Add the style attribute to the element. To do so, Type style="" inside the opening tag for the element you want to change. In the following example, we have added the style attribute to the header text:
<!DOCTYPE html> <html> <body> <h1 style="">This is the header you want to change</h1> </body> </html>
-
4
Type the color: attribute inside the quotation marks. Type «color» with a colon («:») within the quotation marks after the style attribute. So far, your HTML file should look something like the following:
<!DOCTYPE html> <html> <body> <h1 style="color:">This is the header you want to change</h1> </body> </html>
-
5
Type the color you want to change the text to followed by a semi-colon («;»). There are three ways you can express a color. You can type the name of the color, you can enter the RGB value, or you can enter the hex value. For example, to change the color to yellow, you could type yellow; for the color name, rgb(255,255,0); for the RGB value, or #FFFF00; to use the hex value. In the following example, we change the headline color to yellow using the hex value:
<!DOCTYPE html> <html> <body> <h1 style="color:#FFFF00;">This header is now yellow</h1> </body> </html>
Advertisement
Add New Question
-
Question
How would I type bold font in html?
<b></b> is the code for bold text, so you would put your text within that, e.g. <b> hello world </b>.
-
Question
How do I change background colors in HTML?
Use the bgcolor attribute with body tag.
-
Question
How do I change the color of the background?
You will create a similar tag as you did to change the font color. After putting everything in the body tag, you will put the {} brackets and on the inside, type «background-color:(insert desired color).» In code, it should look like this:
body {
color: black;
background-color:gold
}This code gives you black text and a gold background.
See more answers
Ask a Question
200 characters left
Include your email address to get a message when this question is answered.
Submit
Advertisement
-
You can see a list of supported color names and their hex values at http://www.w3schools.com/colors/colors_names.asp
Thanks for submitting a tip for review!
Advertisement
About This Article
Article SummaryX
1. Open the file in a text editor.
2. Find the element you want to change.
3. Type style=″color:#FFFF00;″ in the opening tag.
4. Replace ″#FFFF00″ with your desired color.
Did this summary help you?
Thanks to all authors for creating a page that has been read 1,980,696 times.
Is this article up to date?
Загрузить PDF
Загрузить PDF
В HTML цвет текста меняется с помощью тега <font>, но этот метод больше не поддерживается в HTML5. Вместо указанного тега нужно пользоваться CSS, чтобы задать цвет текста различных элементов страницы. Использование CSS гарантирует, что веб-страница будет совместима с любым браузером.
-
1
Откройте файл HTML. Лучший способ изменить цвет текста — это воспользоваться CSS. Старый тег <font> больше не поддерживается в HTML5. Поэтому воспользуйтесь CSS, чтобы определить стиль элементов страницы.
- Этот метод также применим к внешним таблицам стилей (отдельным файлам CSS). Приведенные ниже примеры предназначены для файла HTML с внутренней таблицей стилей.
-
2
Размеcтите курсор внутри тега <head>. Стили определяются внутри этого тега, если используется внутренняя таблица стилей.
-
3
Введите <style>, чтобы создать внутреннюю таблицу стилей. Когда тег <style> находится внутри тега <head>, таблица стилей, которая находится внутри тега <style>, будет применена к любым элементам страницы. Таким образом, начало HTML-файла должно выглядеть следующим образом:[1]
<!DOCTYPE html> <html> <head> <style> </style> </head>
-
4
Введите элемент, цвет текста которого нужно изменить. Используйте раздел <style>, чтобы определить внешний вид элементов страницы. Например, чтобы изменить стиль всего текста на странице, введите следующее:
<!DOCTYPE html> <html> <head> <style> body { } </style> </head>
-
5
В селекторе элемента введите атрибут color:. Этот атрибут определяет цвет текста выбранного элемента. В нашем примере этот атрибут изменит цвет основного текста, который является элементом, включающим весь текст на странице:
<!DOCTYPE html> <html> <head> <style> body { color: } </style> </head>
-
6
Введите цвет текста. Это можно сделать тремя способами: ввести имя, ввести шестнадцатеричное значение или ввести значение RGB. Например, чтобы сделать текст синим, введите blue, rgb(0, 0, 255) или #0000FF.
<!DOCTYPE html> <html> <head> <style> body { color: red; } </style> </head>
-
7
Добавьте другие селекторы, чтобы изменить цвет различных элементов. Можно использовать различные селекторы, чтобы менять цвет текста разных элементов страницы:
<!DOCTYPE html> <html> <head> <style> body { color: red; } h1 { color: #00FF00; } p { color: rgb(0,0,255) } </style> </head> <body> <h1>Этот заголовок будет зеленым.</h1> <p>Этот параграф будет синим.</p> Этот основной текст будет красным. </body> </html>
-
8
Укажите стилевой класс CSS вместо того, чтобы менять элемент. Можно указать стилевой класс, а затем применить его к любому элементу страницы, чтобы изменить стиль элемента. Например, класс .redtext окрасит текст элемента, к которому применен этот класс, в красный цвет:
<!DOCTYPE html> <html> <head> <style> .redtext { color: red; } </style> </head> <body> <h1 class="redtext"> Этот заголовок будет красным</h1> <p>Этот параграф будет стандартным.</p> <p class="redtext">Этот параграф будет красным</p> </body> </html>
Реклама
-
1
Откройте файл HTML. Можно воспользоваться атрибутами встроенного стиля, чтобы изменить стиль одного элемента страницы. Это может быть полезно, если нужно внести одно-два изменения в стиль, но не рекомендуется для широкомасштабного применения. Чтобы полностью изменить стиль, используйте предыдущий метод.[2]
-
2
Найдите элемент, который нужно изменить.
С помощью атрибутов встроенного стиля можно изменить цвет текста любого элемента страницы. Например, чтобы изменить цвет текста определенного заголовка, найдите его в файле:<!DOCTYPE html> <html> <body> <h1>Этот заголовок нужно изменить</h1> </body> </html>
-
3
К элементу добавьте атрибут стиля. Внутри открывающего тега изменяемого элемента введите style="":
<!DOCTYPE html> <html> <body> <h1 style="">Этот заголовок нужно изменить</h1> </body> </html>
-
4
Внутри "" введите color:. Например:
<!DOCTYPE html> <html> <body> <h1 style="color:">Этот заголовок нужно изменить </h1> </body> </html>
-
5
Введите цвет текста. Это можно сделать тремя способами: ввести имя, ввести шестнадцатеричное значение или ввести значение RGB. Например, чтобы сделать текст желтым, введите yellow;, rgb(255,255,0); или #FFFF00;:
<!DOCTYPE html> <html> <body> <h1 style="color:#FFFF00;">Этот заголовок стал желтым</h1> </body> </html>
Реклама
Советы
- Список поддерживаемых цветов и их шестнадцатеричные значения можно найти на сайте http://www.w3schools.com/colors/colors_names.asp
Реклама
Об этой статье
Эту страницу просматривали 242 817 раз.
Была ли эта статья полезной?
Эта статья — о том, как изменить внешний вид вашего текста или какой-либо его части. К примеру, если вы захотите сделать определённое слово в записи красным. Если вам нужно изменить шрифт или другие параметры текста всего журнала в целом (а не только некоторых слов), то прочтите раздел справки Как изменить шрифт для всего моего журнала?.
Шрифт и другие параметры текста изменяют два различных HTML-тэга: <font> и <span>. У каждого из них есть свои достоинства и недостатки, так что выбирать один из них вам придётся самостоятельно. Ниже будут описаны оба тэга.
Плюсы:
1. Может быть использован для изменения внешнего вида текста вашей Биографии на странице «О пользователе» (вы можете изменить свою биографию здесь), а не только ваших записей в журнале.
2. Начинающим пользователям проще обращаться с этим тэгом, он интуитивно более понятен, чем <span>.
Минус:
1. Не рекомендован к использованию и может некорректно восприниматься перспективными версиями браузеров (хотя поддерживается всеми нынешними). Не поддерживается в XHTML.
<span>
Плюс:
1. Широко используется и будет поддерживаться браузерами значительно дольше, чем <font>. Поддерживается в XHTML.
Минусы:
1. Не может быть использован для изменения внешнего вида Биографии, хотя подходит для модификации текста ваших записей в журнале.
2. Менее удобен и понятен для неопытных пользователей, чем <font>.
Использование <font>
Size
Для изменения размера слов(а) вставьте в текст следующее:
<font size=»размер текста«>А тут — сам текст.</font>
При этом нужно заменить размер текста на требуемый размер. Значение этого параметра — целое число от 1 до 7. Вы также можете вписать «+» или «-» перед числом, если вы хотите увеличить или уменьшить (соответственно) текущий/стандартный размер текста на заданное вами число.
Цвет
Для изменения цвета слов(а) используйте следующее:
<font color=»код цвета«>А тут — сам текст.</font>
Вы должны заменить код цвета на шестнадцатиричный код того цвета, который вам необходим. Список некоторых цветовых кодов можно увидеть вот здесь.
Шрифт
Шрифт слов(а) изменяется вот так:
<font face=»шрифт«>А тут — сам текст.</font>
Вам следует вместо шрифт вписать название того шрифта, который вы хотите использовать (например, sans-serif). При желании вместо одного шрифта можно перечислить несколько, разделив их запятой. Если вы сделаете так, браузер отобразит первый шрифт из перечисленных, если он установлен на компьютере, где просматривается ваша страница; если он не установлен, браузер попытается вывести на экран второй и т. д.
Комбинации
Все вышеперечисленные параметры могут быть использованы в любых комбинациях в одном тэге. Например, следующий код выдаст на экран текст размера 4, голубого цвета и в шрифте comic sans ms:
<font size=»4″ color=»#0000ff» face=»comic sans ms»>Сам текст.</font>
Вот что отобразится:
Сам текст.
Использование <span>
Размер
Для изменения размера слов(а) вставьте в текст:
<span style=»font-size: размер текстаpt;»>А тут — сам текст.</span>
При этом размер текста нужно заменить на тот размер, который вы хотите использовать — на целое число от 1 и выше. Учтите, что тот размер, который вы используете в <span>, и тот, который работает в <font>, никак не соотносятся. В нашем примере размер измеряется в пунктах (или «pt» — от английского «point»). Обычный размер текста — 12 пунктов.
Цвет
Для изменения цвета слов(а) используйте:
<span style=»color: код цвета;»>А тут — сам текст.</span>
При использовании этого тэга следует вместо код цвета вставить нужный шестнадцатиричный код цвета. Список некоторых цветовых кодов размещён вот здесь.
Шрифт
Шрифт слов(а) изменяется следующим образом:
<span style=»font-family: шрифт;»>А тут — сам текст.</span>
Вы должны заменить шрифт на название того шрифта, который вы хотите увидеть (к примеру, sans-serif). Вместо одного шрифта можно перечислить несколько, разделяя их запятой; тогда браузер отобразит первый шрифт из перечисленных, если он установлен на компьютере, где просматривается ваша страница; если он не установлен, браузер попытается вывести на экран второй и т. д.
Комбинации
Вы можете использовать любую комбинацию этих параметров в одном тэге. Например, следующая комбинация выдаст на экран текст размером в 16 пунктов, зелёного цвета и в шрифте trebuchet ms:
<span style=»font-size: 16pt; color: #00ff00; font-family: trebuchet ms;»>Сам текст.</span>
Вот результат:
Сам текст.
С помощью тэга <span> текст можно модифицировать и гораздо более серьёзно. Как именно — можно увидеть в этой статье.
