Меняем цвет шрифта при помощи HTML

Fundamental text and font styling

In this article we’ll start you on your journey towards mastering text styling with CSS. Here we’ll go through all the basic fundamentals of text/font styling in detail, including setting font weight, family and style, font shorthand, text alignment and other effects, and line and letter spacing.

Prerequisites: Basic computer literacy, HTML basics (study Introduction to HTML), CSS basics (study Introduction to CSS).
Objective: To learn the fundamental properties and techniques needed to style text on web pages.

What is involved in styling text in CSS?

If you have worked with HTML or CSS already, e.g., by working through these tutorials in order, then you know that text inside an element is laid out inside the element’s content box. It starts at the top left of the content area (or the top right, in the case of RTL language content), and flows towards the end of the line. Once it reaches the end, it goes down to the next line and flows to the end again. This pattern repeats until all the content has been placed in the box. Text content effectively behaves like a series of inline elements, being laid out on lines adjacent to one another, and not creating line breaks until the end of the line is reached, or unless you force a line break manually using the element.

Note: If the above paragraph leaves you feeling confused, then no matter — go back and review our Box model article to brush up on the box model theory before carrying on.

The CSS properties used to style text generally fall into two categories, which we’ll look at separately in this article:

  • Font styles: Properties that affect a text’s font, e.g., which font gets applied, its size, and whether it’s bold, italic, etc.
  • Text layout styles: Properties that affect the spacing and other layout features of the text, allowing manipulation of, for example, the space between lines and letters, and how the text is aligned within the content box.

Note: Bear in mind that the text inside an element is all affected as one single entity. You can’t select and style subsections of text unless you wrap them in an appropriate element (such as a or ), or use a text-specific pseudo-element like ::first-letter (selects the first letter of an element’s text), ::first-line (selects the first line of an element’s text), or ::selection (selects the text currently highlighted by the cursor).

Fonts

Let’s move straight on to look at properties for styling fonts. In this example, we’ll apply some CSS properties to the following HTML sample:

h1>Tommy the cath1> p>Well I remember it as though it were a meal ago…p> p> Said Tommy the Cat as he reeled back to clear whatever foreign matter may have nestled its way into his mighty throat. Many a fat alley rat had met its demise while staring point blank down the cavernous barrel of this awesome prowling machine. Truly a wonder of nature this urban predator — Tommy the cat had many a story to tell. But it was a rare occasion such as this that he did. p> 

Color

The color property sets the color of the foreground content of the selected elements, which is usually the text, but can also include a couple of other things, such as an underline or overline placed on text using the text-decoration property.

color can accept any CSS color unit, for example:

This will cause the paragraphs to become red, rather than the standard browser default of black, like so:

h1>Tommy the cath1> p>Well I remember it as though it were a meal ago…p> p> Said Tommy the Cat as he reeled back to clear whatever foreign matter may have nestled its way into his mighty throat. Many a fat alley rat had met its demise while staring point blank down the cavernous barrel of this awesome prowling machine. Truly a wonder of nature this urban predator — Tommy the cat had many a story to tell. But it was a rare occasion such as this that he did. p> 

Font families

To set a different font for your text, you use the font-family property — this allows you to specify a font (or list of fonts) for the browser to apply to the selected elements. The browser will only apply a font if it is available on the machine the website is being accessed on; if not, it will just use a browser default font. A simple example looks like so:

This would make all paragraphs on a page adopt the arial font, which is found on any computer.

Web safe fonts

Speaking of font availability, there are only a certain number of fonts that are generally available across all systems and can therefore be used without much worry. These are the so-called web safe fonts.

Most of the time, as web developers we want to have more specific control over the fonts used to display our text content. The problem is to find a way to know which font is available on the computer used to see our web pages. There is no way to know this in every case, but the web safe fonts are known to be available on nearly all instances of the most used operating systems (Windows, macOS, the most common Linux distributions, Android, and iOS).

The list of actual web safe fonts will change as operating systems evolve, but it’s reasonable to consider the following fonts web safe, at least for now (many of them have been popularized thanks to the Microsoft Core fonts for the Web initiative in the late 90s and early 2000s):

Name Generic type Notes
Arial sans-serif It’s often considered best practice to also add Helvetica as a preferred alternative to Arial as, although their font faces are almost identical, Helvetica is considered to have a nicer shape, even if Arial is more broadly available.
Courier New monospace Some OSes have an alternative (possibly older) version of the Courier New font called Courier. It’s considered best practice to use both with Courier New as the preferred alternative.
Georgia serif
Times New Roman serif Some OSes have an alternative (possibly older) version of the Times New Roman font called Times. It’s considered best practice to use both with Times New Roman as the preferred alternative.
Trebuchet MS sans-serif You should be careful with using this font — it isn’t widely available on mobile OSes.
Verdana sans-serif

Note: Among various resources, the cssfontstack.com website maintains a list of web safe fonts available on Windows and macOS operating systems, which can help you make your decision about what you consider safe for your usage.

Note: There is a way to download a custom font along with a webpage, to allow you to customize your font usage in any way you want: web fonts. This is a little bit more complex, and we will discuss it in a separate article later on in the module.

Default fonts

CSS defines five generic names for fonts: serif , sans-serif , monospace , cursive , and fantasy . These are very generic and the exact font face used from these generic names can vary between each browser and each operating system that they are displayed on. It represents a worst case scenario where the browser will try its best to provide a font that looks appropriate. serif , sans-serif , and monospace are quite predictable and should provide something reasonable. On the other hand, cursive and fantasy are less predictable and we recommend using them very carefully, testing as you go.

The five names are defined as follows:

body  font-family: sans-serif; >

Источник

Изменение цвета шрифта в CSS. Коды цветов HTML и CSS

Изменение цвета шрифта в CSS. Коды цветов HTML и CSS

В данной статье я бы хотела более подробно рассказать про то как задать цвет шрифта в css и рассказать про основные форматы задания и коды цветов CSS и HTML.

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

Как задать цвет шрифта css?

Для этого вы можете воспользоваться специальным CSS-свойством color

Где вместо black указывается значение цвета для шрифта текста.

Более подробно о значении цветов в CSS и их форматах я распишу ниже

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

Форматы задания цветов в CSS

Все цвета шрифта вы можете задавать в различных форматах. Вот наиболее распространённые:

где black – это черный цвет html.

Примеры конкретных значений цветов HTML и CSS смотрите ниже.

Где #000000; — это код черного цвета.

Если значение цвета в шестнадцатеричном коде имеет 6 одинаковых цифр или букв, то его можно сократить до трёх.

#ffffff – это код белого цвета

Его можно записать так: #fff

Данный формат представляет собой набор трёх числовых значений от 0 до 255.

Он основывается на использовании трёх цветов, путём смешивания которых получаются все остальные оттенки

R – (red) – числовое значение красного цвета
G – (green) – числовое зелёного
B – (blue) — числовое значение синего

Где 0, 155, 0 – это код зелёного цвета.

Таблица, в которой представлены основные цвета ргб, приведена ниже

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

Где 89, 107, 108 – это ргб код серого цвета, а 0,5 – это уровень прозрачности.

Прозрачность задаётся в виде десятичного значения от 0 до 1, где 0 – цвет совсем не виден, а 1 – цвет максимально непрозрачный

В одной из прошлых статей я писала про определение цвета на сайте. Там я давала несколько полезных инструментов по определению цветов.
Если вы её ещё не читали вот ссылка

Таблица значений основных цветов HTML, RGB и в шестнадцатеричном коде

Название Цвет HTML Шестнадцатеричный код Цвет в формате RGB
Чёрный black #000000 0, 0, 0
Серый gray #8A8A8A 138, 138, 138
Светло-серый silver #C7C7C7 199, 199, 199
Белый white #FFFFFF 255, 255, 255
Красный red #FF0D0D 255, 0, 0
Розовый fuchsia #FF24FF 255, 36, 255
Сиреневый purple #B300B3 179, 0, 179
Синий blue #0909FF 0, 0, 255
Голубой aqua #15FFFF 20, 255, 255
Зелёный green #009B00 0, 155, 0
Салатовый lime #05FF05 5, 255, 5
Жёлтый yellow #FFFF04 255, 255, 4
Оранжевый orange #FFAD15 255, 173, 21

Инструмент для определения значений цветов онлайн

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

Источник

Цвет шрифта HTML

Цвет шрифта на сайте можно задать при помощи HTML-кода. Для этого существует тег font. По определению, тег font служит некой «обёрткой» или «контейнером» для текста, управляя свойствами которого можно изменять оформление текста.

Тег font применяется следующим образом:

Конструктор сайтов "Нубекс"

Самый простой способ, как изменить цвет шрифта в HTML, это использовать атрибут color тега font:

Конструктор сайтов "Нубекс"

Здесь задается синий цвет для слова, обрамленного тегом font.

Но помимо параметра color, тег имеет и другие атрибуты.

Атрибуты тега FONT

Тег font имеет всего три атрибута:

  • color – задает цвет текста;
  • size – устанавливает размер текста;
  • face – задает семейство шрифтов.

Параметр color может быть определен названием цвета (например, “red”, “blue”, “green”) или шестнадцатеричным кодом (например, #fa8e47).

Атрибут size может принимать значения от 1 до 7 (по умолчанию равен 3, что соответствует 13,5 пунктам для шрифта Times New Roman). Другой вариант задания атрибута – “+1” или “-1”. Это означает, что размер будет изменен относительно базового на 1 больше или меньше, соответственно.

Рассмотрим применение этих атрибутов на нашем примере:

     

Конструктор сайтов "Нубекс"

Мы применили тег font к одному слову, задали для него размер 6, оранжевый цвет и семейство шрифтов “Serif”.

Задание цвета текста при помощи CSS

Если вам нужно применить определенное форматирование (например, изменить цвет текста) к нескольким участкам текста, то более правильно будет воспользоваться CSS-кодом. Для этого существует атрибут color. Рассмотрим способ его применения на нашем примере:

    .nubex < color:#fa8e47; font-size: 150%; >.constructor < color: blue; >.saitov 

Конструктор сайтов "Нубекс"

Здесь мы задали синий цвет для слова «Конструктор» (размер его, по умолчанию, 100% от базового), зеленый цвет и размер 125% для слова «сайтов», оранжевый цвет и размер 150% для слова «Нубекс».

Смотрите также:

Источник

Читайте также:  Питон получить размер файла
Оцените статью