Как сделать цветной шрифт в html
Перейти к содержимому

Как сделать цветной шрифт в html

  • автор:

How to Change Text Color in HTML – Font Style Tutorial

Joel Olawanle

Joel Olawanle

How to Change Text Color in HTML – Font Style Tutorial

Text plays a significant role on our web pages. This is because it helps users learn what the web page is all about and what they can do there.

When you add text to your web pages, this text defaults to a black color. But sometimes you will want to change the text color to be more personalized.

For example, suppose you have a darker color as the background of your website. In that case, you’ll want to make the text color a lighter, brighter color to improve your website’s readability and accessibility.

In this article, you will learn how to change the color of your text in HTML. We’ll look at various methods, and we’ll discuss which method is best.

How to Change Text Color Before HTML5

Before the introduction of HTML5, you’d use <font> to add text to websites. This tag takes the color attribute, which accepts the color as a name or hex code value:

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:

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:

But inline styling isn’t the greatest option if your apps get bigger and more complex. So let’s look at what you can do instead.

How to Change Text Color in HTML With Internal or External CSS

Another preferred way to change the color of your text is to use either internal or external styling. These two are quite similar since both use a selector.

For internal styling, you do it within your HTML file’s <head> tag. In the <head> tag, you will add the <style> tag and place all your CSS stylings there as seen below:

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:

Or you could use a class :

Or you could use an id :

Note: As you have seen earlier, with inline CSS, you can use the color name, Hex code, RGB value, and HSL value with internal or external styling.

Wrapping Up

In this article, you have learned how to change an HTML element’s font/text color using CSS. You also learned how developers did it before the introduction of HTML5 with the <font> tag and color attributes.

Also, keep in mind that styling your HTML elements with internal or external styling is always preferable to inline styling. This is because it provides more flexibility.

For example, instead of adding similar inline styles to all your <p> tag elements, you can use a single CSS class for all of them.

Inline styles are not considered best practices because they result in a lot of repetition — you cannot reuse the styles elsewhere. To learn more, you can read my article on Inline Style in HTML. You can also learn how to change text size in this article and background color in this article.

I hope this tutorial gives you the knowledge to change the color of your HTML text to make it look better.

Have fun coding!

Embark on a journey of learning! Browse 200+ expert articles on web development. Check out my blog for more captivating content from me.

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

В этой статье мы познакомимся с возможностями HTML и CSS по смене цвета текста на страницах сайта. Будет рассмотрено несколько вариантов. Для каждого отдельного случая удобен свой конкретный способ.

Для начала отметим, что цвета можно задавать в трех форматах:

  • Название цвета (red, blue, green, . );
  • Шестнадцатеричный формат (#104A00, #0F0, . );
  • Формат rgba (rgba(0,0,0,0.5), . );

На нашем сайте представлена полная палитра и названия html цветов для сайта, где можно выбрать подходящий цвет.

Способ 1. Через html тег <font>

Самым простым способом изменить цвет текста в html является использование тега <font>. Он позволяет изменить цвет, размер и стиль текста. Для этого у него есть три атрибута. Синтаксис:

На странице преобразуется в следующее:

Новая версия стандарта HTML5 не поддерживает тег <font>. Но все современные браузеры понимают и еще видимо будут долго понимать. Этот тег широко распространён в интернете. Что впрочем легко объяснить его доступностью и простотой.

Способ 2. Через атрибут style

Второй способ для изменения цвета шрифта через атрибут style, который можно применять к любым html тегам (<p>, <b>, <u>, <i>, <a>, <strong>, <ul>, <li>, <table>, <div>).

Синий цвет текста

Если текст не изменяет свой цвет, то можно попробовать воспользоваться инструкцией декларацией !important:

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

Способ 3. Через стили CSS

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

Как использовать цветные шрифты в вебе.

Каждый веб-дизайнер умеет задавать цвет шрифта, ведь так? Это одна из первых вещей, которые мы делаем, начиная изучать CSS. Мы выбираем цвет, затем используем стили, чтобы его применить, например color: blue; или color: purple; ,таким образом все знаки в выбранном нами шрифте становятся этого цвета. И только этого цвета.

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

Что ж, с появлением цветных шрифтов Open Type, вы можете сделать именно это.

Взгляните на это изображение с четырьмя разными цветными шрифтами:

Как использовать цветные шрифты в вебе.

Это может выглядеть, как изображения, склеенные в Illustrator, но нет, вы смотрите на живые, редактируемые, читаемые поисковыми системами тексты в браузере.

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

Используем цветные шрифты

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

  • Gilbert на typewithpride.com
  • Abalone на colorfontweek.fontself.com
  • Playbox on colorfontweek.fontself.com
  • Bixa on bixacolor.com

В коде, которым мы добавляем их на страницу, нет ничего нового, это все тот же @font-face , который вы знаете и любите:

Браузеры и поддержка

На текущий момент, если вы хотите использовать цветные шрифты в браузере, вам понадобится либо Firefox, либо Edge, только они имеют полную поддержку цветных шрифтов. Safari ограничивает поддержку только SBIX форматом. Chrome имеет поддержку только на Android и только для формата CBDT. Opera вообще их не поддерживает.

Модификация CSS

На текущий момент мы не можем использовать CSS, чтобы изменить цвета внутри шрифта. Но дизайнер шрифта может выпустить шрифт с несколькими вариациями. И эти вариации можно менять через свойство font-feature-settings .

Мы можем увидеть эту функцию в действии в демо цветного шрифта Trajan от Робина Рэндла с TypeKit.

Цвета фиксированы, даже на ссылках

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

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

Вот небольшой пример кода:

Это даст нам красную линию, подчеркивающую последнее слово:

Как использовать цветные шрифты в вебе.

Заключение

Среди цветных шрифтов и переменных шрифтов , новейшие разработки в Open Type стремятся сделать текст в браузере более интересным и увлекательным. Будущее веб-дизайн типографики выглядит светлым!

How to Change the HTML Font Color

Little figures discussing how to change html font color

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

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

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

Check Out Our Video Guide to Changing the HTML Font Color

Why Change the HTML Font Color?

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

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

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

Try Kinsta Risk-Free

Optimize your admin tasks and budget with $275+ enterprise-level features included free in all WordPress plans. Backed by a 30-day money-back guarantee.

Ways To Define Color

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

Color Name

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

HTML color names

HTML color names.

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

RGB and RGBA Values

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

RGB values

RGB values.

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

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

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

HEX Value

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

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

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

HSL and HSLA Values

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

HSL color values

HSL color values.

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

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

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

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

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

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

The Old: <font> Tags

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

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

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

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

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

The New: CSS Styles

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

Inline CSS

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

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

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

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

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

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

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

Embedded CSS

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

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

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

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

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

And the HSL code would look like this:

External CSS

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

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

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

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

Inline, Embedded, or External?

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

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

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

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

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

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

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

Font Tags or CSS Styles: Pros and Cons

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

HTML Font Tags Pros And Cons

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

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

CSS Pros and Cons

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

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

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

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

Tips for Changing HTML Font Color

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

Use A Color Picker

Color pickers streamline the color selection process.

Color pickers streamline the color selection process.

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

Check the Contrast

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

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

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

Find the Color Using the Inspect Method

Using Inspect to find color codes.

Using Inspect to find color codes.

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

Summary

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

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

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

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

Save time and costs, plus maximize site performance, with $275+ worth of enterprise-level integrations included in every Managed WordPress plan. This includes a high-performance CDN, DDoS protection, malware and hack mitigation, edge caching, and Google’s fastest CPU machines. Get started with no long-term contracts, assisted migrations, and a 30-day money-back guarantee.

Check out our plans or talk to sales to find the plan that’s right for you.

We’ll Migrate Your WordPress Site for Free

Our dedicated team will migrate your WordPress sites to Kinsta, without any work on your end and with minimal service interruption. Migrate risk-free with our 30-day money-back guarantee.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *