Как поменять цвет текста в html в css
Перейти к содержимому

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

  • автор:

Как изменить цвет текста 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 Font Color – How to Style Text in HTML

Kolade Chris

Kolade Chris

CSS Font Color – How to Style Text in HTML

Setting text color on a website you’re building might be confusing at first. But in this article, you’ll learn how to do it.

How to Set Text Color in HTML

In CSS, the background-color property is pretty straightforward for setting the background color of anything.

So what if you want to set the foreground color of something on the page? Especially text, which under normal conditions you wouldn’t want to set a background color for.

There’s no foreground-color property in CSS, so what makes this possible is the color property.

In this article, I will walk you through how to set the color of text using the color property. We’ll also look at the various ways it takes values.

The color property takes values in 4 different ways: named color, hexadecimal color, RGB color, and HSL color. Let’s look at each one now.

Named Colors

As the name implies, you bring in the color property and apply the value by naming the color you want. This may be red, green, blue, orange, crimson, cyan, or any other named color. There are around 147 named colors recognized by browsers.

The basic syntax looks like this:

named-color

Hexadecimal Colors (or just Hex Colors)

Hex values are used to represent colors with a total of 6 characters. They start with the pound/number sign (#), then any number from 0 to 9, and finally any letter from A to F.

The first 2 values stand for red, the next two stand for green, and the last 2 represent blue. With hex values, there’s no limit to the shades of colors you can use.

RGB Colors

RGB stands for red, green, and blue. With RGB colosr, you specify the color in terms of how much red, green, and blue you want. All three are expressed with numbers between 0 and 255.

There is a type of RGB called rgba . The extra ‘a’ stands for alpha, which lets you specify the opacity of the color. It takes a value from 0.0 to 1.0 – 0.0 means 0% opacity, 0.5 means 50% opacity, and 1.0 means 100% opacity.

The basic syntax is rgba(amountOfRed, amountOfGreen, amountOfBlue, alpha) .

You can limit it to rgba(amountOfRed, amountOfGreen, amountOfBlue) if you don’t want an alpha value.

Here’s the syntax for the regular RGB values:

rgb-color

And here it is demonstrating the alpha value in action with 50% (0.5) opacity:

rgb-fifty-percent-opacity

HSL Colors

HSL stands for hue, saturation, and lightness. It is another way of specifying color for text (and anything else that takes color) in CSS.

  • Hue represents the color wheel in 360°. So, 0° is red, 120° is green and 240° is blue.
  • Saturation is the amount of gray in the color, expressed as a percentage. 0% is the shade of gray and 100% is the color itself.
  • Lightness is the amount of darkness and lightness in the color expressed as a percentage. 0% is black and 100% is white.

Just like the RGB colors, you can also set the opacity of the color. So, there’s also hsla.

The full basic syntax is hsl(colorDegree, saturationPercentage, lightnessPercentage, alpha) . You can limit it to hsl(colorDegree, saturationPercentage, lightnessPercentage) in case you don’t want an alpha value.

hsl-color

You can apply a particular opacity to the hsl color like this:

hsl-fifty-percent-opacity-1

Should You Use Named Colors, Hex Colors, RGB Colors, or HSL Colors to Assign Colors?

One of the wonderful things about CSS is that there are multiple ways of doing the same thing. You’ve seen this by applying colors to text.

Since you can apply colors in 4 different ways, you must be wondering which is the best to use.

When you use named colors, you’re kind of limited in how far you can go in applying different shades of colors. Red, green, blue, yellow, or any other named color has a lot of variations you won’t get access to with named colors. You’ll only have access to around 147 predefined colors recognized by browsers.

Hexadecimal colors are very dynamic. They are the most commonly used among developers because your limit is your creativity. With hex colors, you can use various shades and even use a color no one has ever used.

RGB colors are as dynamic as hex colors. Apart from being able to specify how much red, green, and blue you want from 0 to 255, you can also set how transparent you want the color to be with the extra alpha value.

HSL is the most dynamic of all. You get to specify the exact color you want in degrees from 0 to 360 within the color wheel, set how saturated and dark you want it to be in percentages, and also set an opacity from 0.0 to 1.0.

So really, it’s up to you and your use case – and just how creative or specific you want to get.

Conclusion

Applying colors to text helps make your website more attractive to visitors. The right color combo can also help your content become more readable too.

In this article, you have learned how to apply colors to text with the 4 different kinds of values you can use with the color property.

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.

CSS Basics for Typography

Elad Shechter

In 2020 there are a lot of developers and designers who want to learn the basics of CSS. In this series of articles, I will teach you those main topics. In this specific article, I will review the essential CSS properties of typography while using many visual examples.

font-family

This font-family property is used to declare what font we want to use. It can receive an array of fonts. This can be useful to us for two reasons:

  1. If the first font isn’t working in a specific operating system, the browser will use the next font until something matches it.
  2. If the font has missed some of the characters, it will fill in the missing characters from the next font at the list.

font-weight

This property, like his name, is for declaring the font-weight of the text. The default value of this property is normal , and the second common value of it is bold .

In more advanced fonts there are more than two states. Instead of using names in the values, these fonts are using numeric values: 100 / 200 / 300 / 400 / 500 / 600 / 700 / 800 / 900 and 950 . Which are equal to the common mapping names (in design apps), see table:

The normal keyword is equal to 400 value, and the bold keyword is equal to 700 value. Examples:

font-size

This property, like his name, is for declaring the font-size of the text. Even today, the most common sizing unit is pixels. Example:

From my perspective, it is better to control the font-size with rem units. If you want to know more about how to work with rem units, you can read my article “Update your font-size to REM units”.

line-height

This property is telling the browser the height of the line in ratio to the text-size . This property can get fixed value like pixel, but the most common way is to give it a value of ratio without any unit.

The line-height property, is a type of inherited property, which usually means you declare it one time in the root element, and it will affect all the elements on our website. This way if we have different font-size in inner elements, the line-height will stay with the same ratio, and we won’t need to declare it multiple times. Example:

font-style

We use it to update the text font into an italic variant state.

Text color property

The color property is used to color the text. It can receive color keywords, for example, red , magenta . It can receive a HEX color code and color functions like RGB and HSL. If you want to know more about CSS colors, you can read my article “Why CSS HSL Colors are Better!”.

text-align

This property, like his name, is to control the alignment of text in its reading axis(inline-axis). Besides the possibilities to align left and right , we have the center value and the less known justify value, which aligns the text in both ways.

Besides, there is an extensive property, text-align-last , which allows you to differentiate the last line from all the other lines. For more info: text-align-last in MDN.

direction

The direction property sets the direction of text, table columns, flexbox, grids, and more. It has two values:

  1. ltr value — for Latin languages that are read from left to right.
  2. rtl value — for Semitic languages that are read from right to left.

When using the direction property the text-align property is being updated automatically as well in the same direction unless it is defined otherwise. Example:

vertical-align

This property is used mainly for vertical inline text content. The main common values are baseline (default value), text-top , and text-bottom which are relative to the line-height of the text in the container.

There are more values like top and bottom that can act differently only if the line-height of to row is different from the line-height of the inline elements.

This property can be used even unit values which are positioned according to the baseline value, which means 0px = baseline , with this, you can play with negative & positive values, for example -2px or 2px .

Note: this vertical alignment is good for text elements. For vertical alignment of boxes, it is better to use CSS flexbox.

text-decoration

This property’s most used case is for adding underline to links, and it could also be used for creating overline and line-through . Example:

But in the last years, this property has been given a lot of extensions, and now you can use all the values together, for example:

Another possibility we now have is to play with the style of the lines and with their color.

text-transform

The text-transform property specifies how to capitalize on texts. We use it to make text appear in all-uppercase or all-lowercase, or to make each word capitalized.

letter-spacing

The letter-spacing property, as his name is, decreases or increases the spacing between the letters of the words. When using this property with px units, you can use fragments of pixels for example 0.1px . To decrease the spacing, this property can get negative values as well, like -1.5px , for example.

word-spacing

The letter-spacing property, as his name, allows us to define the space between the words.

text-indent

The indent property is used to indent the first line in a paragraph. Inside with a positive value or outside with a negative value.

::first-letter

The ::first-letter pseudo-element selector allows us to style the first letter in different styles from the regular text in paragraphs, for example.

Besides the ::first-letter pseudo-element, there is the ::first-line pseudo-element, which allows you to style the first-line of a paragraph differently. Because I haven’t seen a common use for it, I have decided not to give it a big stage in my article, but just to notify you that it exists.

text-shadow

The text-shadow property allows us to add shadow to text. For it to work, we need to provide it with at least the offset-x and the offset-y of the shadow. If we provide only these two values, the shadow will be left without a spread and with the same color of the text.

The third numeric value will be the spread of the shadow. We can also give it a different color value, in the beginning, or the end of the value.

Besides, we can add multiple text-shadows, using a comma in the value.

text-stroke

The text-stroke property is a non-standard property that works in all main browsers. It works with the -webkit prefix, even on Firefox & old Edge. The property receives two values, stroke-width and stroke-color.

More and More and More!

There are more properties of CSS for typography and big new topics like Variable Fonts, which are dynamic. But in this article, I have tried to show the main basic elements to control typography with CSS.

If this topic interests you, you can continue and explore this vast topic in CSS. Here some more properties and topics we haven’t talked about: Variable Fonts, font-variant , text-justify , unicode-bidi , all the ways of breaking words in CSS, and I may have missed several more��.

To Summarize

In this article, my primary purpose was to show the most useful properties for CSS typography and to provide you with this knowledge.

Final Words

I hope I inspired you and showed you some new possibilities.
If you like this post, I would appreciate applause and sharing ��.

I create lots of content on CSS. Be sure to follow me via Twitter, Linkedin, and Medium.

Also, you can see all of my content on my website: eladsc.dev.

Who Am I?

I am Elad Shechter, a Web Developer specializing in CSS & HTML design and architecture.

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

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