Font color setting in css

How to set font color in HTML?

We use the style attribute to set the font color in HTML. The style attribute specifies an inline style for an element, with the CSS property color. The attribute is used with the HTML

tag, with the CSS property color. HTML5 do not support the tag, so the CSS style is used to add font color. The tag deprecated in HTML5.

Syntax

Example

In the example below, we set the font color of the text inside the

tag.

DOCTYPE html> html> head> title>HTML Font colortitle> head> body> h1>Productsh1> p style="color:blue">This is demo content.p> body> html>

Example

Following is the example program to set font color in HTML.

DOCTYPE html> html> head> style> body < background-color: rgb(20,30, 1); >style> h1 style="color: azure">HTML Articlesh1> head> body> body> html>

Example: Specifying internal style

We can also specify internal style for an element, with the CSS property color to set font color in HTML. Following is the example program for internal style sheet to set font color in HTML.

DOCTYPE html> html> head> style> body < background-color: rgb(20,30, 1); >h1 < color: cyan; >style> h1>HTML Articlesh1> head> body> body> 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.

Thank you for reading, and keep coding.

Источник

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

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

Цвет шрифта можно изменять стилизации внутри HTML-документа . Однако рекомендуется использовать именно внешние таблицы CSS-стилей .

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

.

Как поменять цвет шрифта в 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 Color with CSS in HTML?

How To Change Font Color with CSS in HTML?

Cascading Style Sheet or CSS is used to change attributes of the HTML elements. We can change font size, color, shape, size, length, etc with CSS. In this tutorial, we will learn how to change the font color of different elements in HTML with CSS.

Font Color Syntax

Font color has very simple syntax where we use “ tag and color attributes with the color data in 3 different representation format name , hex number and RGB number .

Change Font Color with Color Name

As stated previously we can specify the color with its human-friendly name like red , blue etc. This is the easiest way to describe the color. In this example, we will set the font color to the blue .

This is some red text!

This is some blue text!

This is some green text!

This is a normal text without font color

Change Color with Color Name

Change Font Color with Hex Number

Another way to specify the font color is by using hex numbers. Colors have high precision hexadecimal numbers where the color can be precisely defined. Hexadecimal numbers provide us the ability to select very detailed colors that can not be expressed with the color name. Before providing the hexadecimal number we need to put a # in order to specify the hexadecimal number. In this example, we will use the hexadecimal values of red , blue and green .

This is some red text!

This is some blue text!

This is some green text!

This is a normal text without font color

Change Font Color with Hex Number

Change Font Color with RGBA Number

RGB or Red, Green, Blue, Alpha is a very old coloring system that can be also used for font color specification. most of the colors consist of a mixture of main colors Red, Blue, and Green. We can express these colors with the weight of these main colors. We have to provide 4 values where we will prefix it with the RGB and surround it with parenthesis. The last alpha value is used to set opacity where 1 means opaque and 0 means transparent. We can also set floating numbers like 0.34 , 0.54, etc.

This is some red text!

This is some blue text!

This is some green text!

This is a normal text without font color

Change Font Color with Inline CSS

CSS font colors can be set in two different ways where we can use set into the HTML tag directly or with an external CSS file. Actually, we have used inline CSS by setting an HTML CSS color attribute like below.

This is some red text!

This is some blue text!

This is some green text!

This is a normal text without font color

Change Font Color with External CSS

Another way is using an external CSS file where we have to specify it in the header of the HTML file. The external CSS file will contain the following CSS code which will change p or paragraph elements font color to the red.

We can also use the hexadecimal or RGB presentation of the colors like below.

If the external CSS file has the name mysite.css it can be imported like below with link element.

ChangeFont Color with CSS Inside Head Tag

We can use tag in order to specify a generic CSS code where we do not need to use an external CSS file. We will use tag a put our font color changer CSS code. In this example, we will set the font color of p or paragraph tag to the blue.

Change Multiple Tag Font Color

If we want to change multiple types of tags font color with a single and simple CSS code we need to specify them like below. In this example, we will set the h1 , h2 , h3 , h4 font colors to the blue with an external CSS code.

Источник

Читайте также:  Result11 stavrcoi ru result php
Оцените статью