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

Как сделать текст другим цветом в html

  • автор:

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.

How can I change my font color with html?

I’m making a web page where I want the color of the font to be red in a paragraph but I’m not sure how to do this.

I was using FrontPage for building web pages before so this HTML stuff is really new to me. What is the best way to do this?

Stephen Kennedy's user avatar

4 Answers 4

Where «error» is defined in your stylesheet:

The preferred way to do this is using Cascading Style Sheet (CSS). This allows you to edit the visual aspects of the site without having to deal much with the HTML code itself.

Where [tag] can be anything. For example «p» (paragraph), «span», «div», «ul», «li».. etc.

and where [css] is any valid CSS. For example «color:red; font-size:15px; font-weight:bold»

The recommended way to add style to a html element is by assigning it a «class» (a identifier that can be repeated on the document) or a «id» a unique identifier that shall not be repeated in the document.

Where tag is any html valid tag. id is a unique arbitrary name and class is an arbitrary name that can be repeated.

Then in the CSS (inside the tags of your document):

For this example and to keep it simple to new users I named the class «red». However isn’t the best example of how to name . Better to name CSS classes after their semantic meaning, rather than the style(s) they implement. So or might be more appropriate. ( Thanks to Grant Wagner for pointing that out )

Brief CSS Explanation :

Since most of the answers you’re getting are all mentioning CSS, I’ll add a small guide on how it works:

Where to put CSS

First of all, you need to know that CSS should be added inside the tags of your document. The tags used to define where the CSS is going to be are:

This is called embedded CSS since it’s inside the document. However, a better practice is to link «include it» directly from an external document by using the following tags:

Where file.css is the external file you want to include into the document.

The benefits of using the «link» tag is that you don’t have to edit in-line CSS. So lets say if you have 10 HTML documents and you want to change the color of a font you just need to do it on the external CSS file.

This two ways of including CSS are the most recommended ways. However, there’s one more way that’s by doing in-line CSS adjustments, for example:

CSS General Structure

When you code write CSS, the first thing you need to know is what are classes and what are id’s. Since I already mentioned what they do above I’m going to explain how to use them.

When you write CSS you first need to tell which elements you’re going to «select», for example:

Lets say we have a «div» element with the class «basic» and we want it to have a black background color, a white font, and a gray border.

To do this we first need to «select» the element:

Since we’re using a class we use a «.» in front of the identifier which in this case is: «basic», so it will look like this:

This is not the only way, because we’re telling that ANY element that has the class «basic» will be selected, so lets say we JUST want the «div» elements. To do this we use:

So for our example it will look like this:

Now we’ve selected the «div» with the class «body». Now we need to apply the visual style we wish. We do this inside the brackets :

With this, we just applied successfully a visual style to all «div» elements that have the «basic» class attached.

Remember this doesn’t just apply for «class» it also applies for «id» but with a slight change, here an example of the final code but instead of a class we’ll just say it’s a «id»

For a complete guide to CSS you can visit this link: http://www.w3schools.com/css/

Remember:

Keep your HTML Code clean and use CSS to modify ANY visual style that’s needed. CSS is really powerful and it’ll save you a lot of time.

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

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

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

Навигация по статье:

Если ваш сайт сделан на одной из CMS, то для изменения цвета текста вы можете использовать встроенный функционал визуального редактора, однако такая функция там не всегда есть, а ставить ради этого дополнительный модуль или плагин не всегда есть смысл.

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

Изменения цвета текста средствами HTML

К счастью в HTML есть специальный тег с атрибутом color, в котором можно указать нужный цвет текста.

Значение цвета можно задавать несколькими способами:

  • При помощи кодового названия (Например: red, black, blue)
  • В шестнадцатиричном формате (Например: #000000, #ccc)
  • В формате rgba (Например: rgba(0,0,0,0.5))

Таким образом вы можете изменить цвет у целого абзаца, слова или одной буквы, обернув то что вам нужно в тег <font>

Как изменить цвет текста в HTML с использованием CSS?

Для изменения цвета текста для определённого абзаца или слова можно присвоить ему класс, а затем в CSS файле задать для этого класса свойство color.

Выглядеть это будет так:

HTML


CSS

Вместо color-text вы можете указать свой класс.

Если вы не хотите лезть в CSS файл чтобы внести изменения, то можно дописать CSS стили прямо в HTML коде станицы, воспользовавшись тегом <style>.

  1. 1. Находи вверху HTML страницы тег </head>. Если ваш сайт работает на CMS, то этот фрагмент кода находится в одном из файлов шаблона. Например: header.php, head.php или что-то наподобие этого в зависимости от CMS.
  2. 2. Перед строкой </head> добавляем теги <style>…</style>.
  3. 3. Внутри этих тегов задаём те CSS свойства, которые нам нужны. В данном случае color:

Этот способ подходит если вам нужно изменить цвет сразу для нескольких элементов на сайте.

Если же такой элемент один, то можно задать или изменить цвет текста прямо в HTML коде.

Изменяем цвет в HTML коде при помощи атрибута style

Для этого добавляем к тегу для которого нам нужно изменить цвет текста атрибут style.

Здесь же при необходимости через ; вы можете задать и другие CSS свойства, например, размер шрифта, жирность и так далее.

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

Так же вы должны знать, что есть такое понятие как приоритет стилей. Так вот когда вы задаёте цвет текста или другие стили в html при помощи атрибута style, то у этих стилей приоритет будет выше чем если вы их зададите в CSS файле (при условии что там не использовалось правило !important)

Чтобы изменить цвет текста отдельного слова, фразы или буквы мы можем обернуть их в тег span и задать ему нужный цвет.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

# RR GG BB

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

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

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

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

# R G B

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

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

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

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

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

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

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

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