- Как поменять цвет текста CSS
- Как поменять цвет шрифта в CSS — добавляем стили
- How to Change Font and Text Color Using CSS
- Scope
- Basic struture of a HTML file
- Setting up an HTML file
- Learning how to change text color in CSS
- Using color keywords to change text color in CSS
- Using Hexadecimal values to change text colors in CSS
- Using RGBA color values to change text color in CSS
- Conclusion
- How to Change Text Color in HTML – Font Style Tutorial
- How to Change Text Color Before HTML5
- Welcome to freeCodeCamp! // Using internal/external CSS selector
- How to Change Text Color in HTML
- How to Change Text Color in HTML With Inline CSS
- How to Change Text Color in HTML With Internal or External CSS
- Wrapping Up
Как поменять цвет текста CSS
Хороший дизайн – важная составляющая любого успешного сайта. CSS даёт полный контроль над внешним видом текста. В том числе и над тем, как изменить цвет текста в HTML .
Цвет шрифта можно изменять стилизации внутри HTML-документа . Однако рекомендуется использовать именно внешние таблицы CSS-стилей .
Внутренние стили, которые задаются в заголовке документа, принято использовать на маленьких одностраничных сайтах. В больших проектах лучше избегать внутренней стилизации, так как это сопоставимо с устаревшим тегом font , которым мы пользовались много лет назад. Строчные стили значительно усложняют обслуживание кода, так как они указываются непосредственно перед каждым элементом на странице. Сегодня вы узнаете, как задать цвет текста в CSS и стилизовать тег
.
Как поменять цвет шрифта в CSS — добавляем стили
В этом примере понадобится веб-страница с разметкой и отдельный CSS-файл , подключаемый внутри HTML-кода .
В HTML-документе будет несколько элементов, но мы будем работать только параграфом. Вот так меняется цвет текста внутри тегов
при помощи внешней таблицы стилей.
Значения цветов можно указывать при помощи названий, RGB или шестнадцатеричных значений.
- Добавляем атрибут style к тегу
:
Элементы
на странице станут чёрными.
Перед тем, как изменить цвет текста в HTML , нужно понимать, что в данном примере используется название цвета black . Несмотря на то, что это один из способов указания цвета в CSS , он имеет определенные ограничения.
Нет ничего страшного в том, чтобы использовать названия black ( чёрный ) и white ( белый ). Но этот способ не позволяет указывать конкретные оттенки. Поэтому для указания цвета чаще используются шестнадцатеричные значения:
Этот CSS-код также сделает элементы
чёрными, так как hex-код #000000 обозначает чёрный цвет. Также можно использовать сокращённый вариант #000 , и результат будет тем же.
Как отмечалось ранее, hex-значения отлично подходят в тех случаях, когда необходимо использовать сложные цвета.
Данное hex-значение придаст тексту синий цвет. Но в отличие от простого blue этот код позволяет указать конкретные оттенки синего. В данном примере получится тусклый серо-синий цвет.
Перейдём к RGBA-значениям . RGBA поддерживают все современные браузеры, так что этот метод можно использовать, не беспокоясь о запасных вариантах:
Это RGBA-значение обеспечит всё тот же тусклый, серо-синий цвет. Первые три значения отвечают за красный, зелёный и синий, а последняя цифра — за уровень непрозрачности. « 1 » означает « 100% ». То есть, текст будет полностью непрозрачным.
Если сомневаетесь в поддержке браузерами, то цвета можно указывать следующим образом:
В этом синтаксисе сначала идет hex-значение , которое затем переписывается RGBA-значением . Это значит, что устаревшие браузеры, в которых нет поддержки RGBA , будут использовать первое значение и игнорировать второе. Современные браузеры будут использовать второе значение. Это нужно учитывать, чтобы знать, как поменять цвет текста в CSS.
Валентин Сейидов автор-переводчик статьи « How to Change the Font Color with CSS »
Пожалуйста, оставляйте ваши комментарии по текущей теме материала. Мы крайне благодарны вам за ваши комментарии, дизлайки, отклики, лайки, подписки!
How to Change Font and Text Color Using CSS
It is quite interesting to note that several websites could very well have the same HTML code, but their styling or CSS is what would make them different! Talking about CSS in particular, graphic designer displays their creativity through it. Not only does it give the web designer control over the appearance of the web pages, but it also aids in creating a visual hierarchy through parameters like shape, color, space, and size.
Scope
In this tutorial, we will learn the following-
- We will start with a brief introduction to an HTML file and how to set up it.
- Then, we will learn about how to change the text color in CSS and the various methods to do so-
- Using Color Keywords
- Using Hexadecimal Values
- Using RGBA Color Values
Basic struture of a HTML file
The presentation of a document written in markup languages such as HTML is described using a style sheet language known as CSS. HTML stands for HyperText Markup Language, whereas CSS is the abbreviation for Cascading Style Sheets. They are unique in their syntax. While HTML could be regarded as the structure of a website, CSS is the styling done on the structure.
Setting up an HTML file
Let’s create an HTML file named Index.html. We will call it the CSS file style.css. Using this file, you will learn how to change text color in CSS.
After adding the required boilerplate, the contents of Index.html are as follows –
Learning how to change text color in CSS
We can change text color in CSS quite easily. There are three techniques we can use, which are as follows-
Using color keywords to change text color in CSS
To change text color in CSS, you can use the color keywords to achieve this.
- Color keywords are nothing but the names of the colors like red, blue, yellow, etc.
- We will change the font color of the heading or the h1 tag in Index.html to red.
- To do this, you will go to the external CSS file, which is style.css . You should add the following code to it –
The font color will successfully be changed to red from the default color.
Using Hexadecimal values to change text colors in CSS
More often than not, while designing a website, there could be a specific color scheme or brand kit that you might be required to use. This cannot be possible if you are using color keywords such as blue, green, red, etc. So you can now learn to use the hexadecimal values to change the font color of the paragraph elements.
Let’s take a look at how you can achieve this –
Add the following code to style.css. This will change the color of the paragraph elements to a specific shade of blue of our choice.
Using RGBA color values to change text color in CSS
RGBA color value manipulation is also a good way to change text color in CSS. The RGBA abbreviation stands for Red, Blue, Green, and Alpha . The Alpha value controls the transparency of the color. For example, if the value of Alpha is set to 1: it means the color is completely opaque. On the other hand, when it is 0.75, it suggests the color would be only 75% opaque or 25% transparent.
So here is how you will change the color of our h2 tag in Index.html using the RGBA color values –
Once the above code is added to the style.css file, you can say that you know how to change font color in CSS.
Now you know how to change font color in CSS efficiently. Although this can be achieved through internal CSS and inline CSS as well, the best practice remains using an external CSS file, just like you did in this tutorial.
So now, the next time someone asks you, “How to change the font color using CSS?” you will not only be able to tell them how to do that but also share some tips about different font properties as well!
Conclusion
In this tutorial, we covered the three different ways you can change font color in CSS. To sum it up, they are-
- Using color keywords– You can simply use color keywords which are nothing but the name of colors, to style your HTML file.
- Using Hexadecimal values– Hex codes or hexadecimal values enable you to get intermediate colors and specific colors, which is not possible while using color keywords. So now, if you are asked to follow a particular color scheme or a brand kit, you know which technique to use in CSS.
- Using RGBA values– If you are aware of the values of Red, Blue, Green, and Alpha to be used, then this is the best way for you to change text color in CSS. As a designer, you can also manipulate the transparency of the color using the Alpha attribute of this method.
How to Change Text Color in HTML – Font Style Tutorial
Joel Olawanle
Text plays a significant role on our web pages. This is because it helps users learn what the web page is all about and what they can do there.
When you add text to your web pages, this text defaults to a black color. But sometimes you will want to change the text color to be more personalized.
For example, suppose you have a darker color as the background of your website. In that case, you’ll want to make the text color a lighter, brighter color to improve your website’s readability and accessibility.
In this article, you will learn how to change the color of your text in HTML. We’ll look at various methods, and we’ll discuss which method is best.
How to Change Text Color Before HTML5
Before the introduction of HTML5, you’d use to add text to websites. This tag takes the color attribute, which accepts the color as a name or hex code value:
Welcome to freeCodeCamp. // Or Welcome to freeCodeCamp.
This tag got depreciated when HTML5 was introduced. This makes sense because HTML is a markup language, not a styling language. When dealing with any type of styling, it is best to use CSS, which has the primary function of styling.
This means for you to add color to your web pages, you need to make use of CSS.
In case you are in a rush to see how you can change the color of your text, then here it is:
// Using inline CSS
Welcome to freeCodeCamp! // Using internal/external CSS selector
Suppose you are not in a rush. Let’s briefly dive right in.
How to Change Text Color in HTML
You can use the CSS color property to change the text color. This property accepts color values like Hex codes, RGB, HSL, or color names.
For example, if you want to change the text color to sky blue, you can make use of the name skyblue , the hex code #87CEEB , the RGB decimal code rgb(135,206,235) , or the HSL value hsl(197, 71%, 73%) .
There are three ways you can change the color of your text with CSS. These are using inline, internal, or external styling.
How to Change Text Color in HTML With Inline CSS
Inline CSS allows you to apply styles directly to your HTML elements. This means you are putting CSS into an HTML tag directly.
You can use the style attribute, which holds all the styles you wish to apply to this tag.
You will use the CSS color property alongside your preferred color value:
// Color Name Value
Welcome to freeCodeCamp!
// Hex ValueWelcome to freeCodeCamp!
// RGB ValueWelcome to freeCodeCamp!
// HSL ValueWelcome to freeCodeCamp!
But inline styling isn’t the greatest option if your apps get bigger and more complex. So let’s look at what you can do instead.
How to Change Text Color in HTML With Internal or External CSS
Another preferred way to change the color of your text is to use either internal or external styling. These two are quite similar since both use a selector.
For internal styling, you do it within your HTML file’s tag. In the tag, you will add the tag and place all your CSS stylings there as seen below:
While for external styling, all you have to do is add the CSS styling to your CSS file using the general syntax:
The selector can either be your HTML tag or maybe a class or an ID . For example:
// HTML
Welcome to freeCodeCamp!
// CSS p// HTML
Welcome to freeCodeCamp!
// CSS .my-paragraph// HTML
Welcome to freeCodeCamp!
// CSS #my-paragraphNote: As you have seen earlier, with inline CSS, you can use the color name, Hex code, RGB value, and HSL value with internal or external styling.
Wrapping Up
In this article, you have learned how to change an HTML element’s font/text color using CSS. You also learned how developers did it before the introduction of HTML5 with the tag and color attributes.
Also, keep in mind that styling your HTML elements with internal or external styling is always preferable to inline styling. This is because it provides more flexibility.
For example, instead of adding similar inline styles to all your
tag elements, you can use a single CSS class for all of them.
Inline styles are not considered best practices because they result in a lot of repetition — you cannot reuse the styles elsewhere. To learn more, you can read my article on Inline Style in HTML. You can also learn how to change text size in this article and background color in this article.
I hope this tutorial gives you the knowledge to change the color of your HTML text to make it look better.
Embark on a journey of learning! Browse 200+ expert articles on web development. Check out my blog for more captivating content from me.