Setting Font Size

Как сделать красивый шрифт в html: размеры, цвета, теги шрифтов html

В html размер шрифта играет важную роль. Он позволяет обратить внимание пользователя на важную информацию, размещенную на странице сайта. Хотя важен не только размер букв, но и их цвет, толщина и даже семейство.

Теги и атрибуты при работе со шрифтами html

Язык гипертекста обладает большим набором средств для работы со шрифтами. Ведь именно форматирование текста является основной задачей html .

Рассмотрим теги, которые используются для работы со шрифтами в html и их атрибуты. Основным из них является тег . С помощью значений его атрибутов можно задать несколько характеристик шрифта:

  • face – используется для установки семейства шрифтов текста, которые будут использованы внутри тега . Поддерживается сразу несколько значений перечисленных через запятую.
 

Форматируется только тот текст, который расположен между частями парного тега font. Остальной текст отображается стандартным шрифтом, установленным по умолчанию.

Также в html существует ряд парных тегов, задающих лишь одно правило форматирования. К ним относятся:

  • — задает в html жирный шрифт. Тег по действию аналогичный предыдущему;
  • — размер больше установленного по умолчанию;
  • — меньший размер шрифта;
  • — наклонный текст ( курсив ). Аналогичный ему тег ;
  • — текст с подчеркиванием;
  • — зачеркнутый;
  • — отображение текста только в нижнем регистре;
  • — в верхнем регистре.

Обычный текст

Жирный текст

Жирный текст

Больше обычного

Меньше обычного

Курсив

Курсив

С подчеркиванием

Зачеркнутый

Возможности атрибута style

Кроме описанных тегов существует еще несколько способов, как изменить шрифт в html . Одним из них является применение универсального атрибута style . С помощью значений его свойств можно задавать стиль отображения шрифтов:

1) font-family – свойство устанавливает семейство шрифта. Возможно перечисление нескольких значений.
Изменение шрифта в html на следующее значение произойдет, если предыдущее семейство не установлено в операционной системе пользователя .

font-family: имя шрифта [, имя шрифта[, . ]]

2) font-size – задается размер от 1 до 7. Это один из основных способов того, как в html можно увеличить шрифт.
Синтаксис написания:

font-size: абсолютный размер | относительный размер | значение | проценты | inherit

Размер шрифта можно также задать:

  • В пикселях;
  • В абсолютном значении ( xx-small, x-small, small, medium, large );
  • В процентах;
  • В пунктах ( pt ).

 

font-size:7

font-size:24px

font-size: x-large

font-size: 200%

font-size:24pt

3) font-style – устанавливает стиль написания шрифта. Синтаксис:

font-style: normal | italic | oblique | inherit
  • normal –нормальное написание;
  • italic – курсив;
  • oblique – шрифт с наклоном вправо;
  • inherit – наследует написание родительского элемента.

Пример того, как поменять шрифт в html с помощью этого свойства:

font-style:inherit

font-style:italic

font-style:normal

font-style:oblique

4) font-variant – переводит все строчные буквы в заглавные. Синтаксис:

font-variant: normal | small-caps | inherit

Пример того, как изменить шрифт в html этим свойством:

font-variant:inherit

font-variant:normal

font-variant:small-caps

5) font-weight – позволяет установить толщину написание текста ( насыщенность ). Синтаксис:

font-weight: bold|bolder|lighter|normal|100|200|300|400|500|600|700|800|900
  • bold – устанавливает полужирный шрифт html;
  • bolder – жирнее относительно normal;
  • lighter –менее насыщенное относительно normal;
  • normal – нормальное написание;
  • 100-900 – задается толщина шрифта в числовом эквиваленте.

font-weight:bold

font-weight:bolder

font-weight:lighter

font-weight:normal

font-weight:900

font-weight:100

Свойство font и цвет шрифта html

Font является еще одним контейнерным свойством. Внутри себя оно объединило значения нескольких свойств, предназначенных для изменения шрифтов. Синтаксис font :

font: [font-style||font-variant||font-weight] font-size [/line-height] font-family | inherit

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

  • caption – для кнопок;
  • icon – для иконок;
  • menu – меню;
  • message-box –для диалоговых окон;
  • small-caption – для небольших элементов управления;
  • status-bar – шрифт строки состояния.

font:icon

font:caption

font:menu

font:message-box

small-caption

font:status-bar

font:italic 50px bold "Times New Roman", Times, serif

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

color:#00FF99

color:blue

color:rgb(0, 255, 153)

Русскоязычные шрифты и их поддержка

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

  • Arial Black ;
  • Arial ;
  • Comic Sans MS ;
  • Courier New ;
  • Georgia ;
  • Lucida Console ;
  • Lucida Sans Unicode ;
  • Palatino Linotype ;
  • Tahoma ;
  • Times New Roman ;
  • Trebuchet MS ;
  • Verdana .
    Если этого количества мало, то на просторах интернета хватает сайтов, где можно скачать шрифт на любой вкус. Еще можно разработать свой шрифт. Но это уже совсем другая история. И она будет написана уже другим шрифтом.

Источник

HTML — Fonts

Fonts play a very important role in making a website more user friendly and increasing content readability. Font face and color depends entirely on the computer and browser that is being used to view your page but you can use HTML tag to add style, size, and color to the text on your website. You can use a tag to set all of your text to the same size, face, and color.

The font tag is having three attributes called size, color, and face to customize your fonts. To change any of the font attributes at any time within your webpage, simply use the tag. The text that follows will remain changed until you close with the tag. You can change one or all of the font attributes within one tag.

Note −The font and basefont tags are deprecated and it is supposed to be removed in a future version of HTML. So they should not be used rather, it’s suggested to use CSS styles to manipulate your fonts. But still for learning purpose, this chapter will explain font and basefont tags in detail.

Set Font Size

You can set content font size using size attribute. The range of accepted values is from 1(smallest) to 7(largest). The default size of a font is 3.

Example

     Font size = "1" 
Font size = "2"
Font size = "3"
Font size = "4"
Font size = "5"
Font size = "6"
Font size = "7"

This will produce the following result −

Relative Font Size

You can specify how many sizes larger or how many sizes smaller than the preset font size should be. You can specify it like or

Example

     Font size = "-1" 
Font size = "+1"
Font size = "+2"
Font size = "+3"
Font size = "+4"

This will produce the following result −

Setting Font Face

You can set font face using face attribute but be aware that if the user viewing the page doesn’t have the font installed, they will not be able to see it. Instead user will see the default font face applicable to the user’s computer.

Example

     Times New Roman 
Verdana
Comic Sans MS
WildWest
Bedrock

This will produce the following result −

Specify alternate font faces

A visitor will only be able to see your font if they have that font installed on their computer. So, it is possible to specify two or more font face alternatives by listing the font face names, separated by a comma.

When your page is loaded, their browser will display the first font face available. If none of the given fonts are installed, then it will display the default font face Times New Roman.

Note − Check a complete list of HTML Standard Fonts.

Setting Font Color

You can set any font color you like using color attribute. You can specify the color that you want by either the color name or hexadecimal code for that color.

Note − You can check a complete list of HTML Color Name with Codes.

Example

     This text is in pink 
This text is red

This will produce the following result −

The Element

The element is supposed to set a default font size, color, and typeface for any parts of the document that are not otherwise contained within a tag. You can use the elements to override the settings.

The tag also takes color, size and face attributes and it will support relative font setting by giving size a value of +1 for a size larger or −2 for two sizes smaller.

Example

      

This is the page's default font.

Example of the <basefont> Element

This is darkgray text with two sizes larger

It is a courier font, a size smaller and black in color.

This will produce the following result −

Источник

HTML Font Style – How to Change Text Color and Size with an HTML Tag

Kolade Chris

Kolade Chris

HTML Font Style – How to Change Text Color and Size with an HTML Tag

When you code in HTML and add some text, you don’t want to leave it like that. You want to make that text look good.

And to do that, you need to change their appearance through the color and font-size properties of CSS.

In this tutorial, I will show you two different ways you can make your HTML texts look good.

Basic font-size Syntax

How to Change Text Size and Text Color in the HTML Tag

You can change the color and size of your text right inside its tag with the color and font-size properties. This is known as inline CSS. You do it with the style attribute in HTML.

In the HTML code below, we will change the color and size of the freeCodeCamp text.

unstyled-font

It looks like this in the browser:

To change the size of the text, you’ll use the style attribute, and then set a value with the font-size property like this:

text-size

The text now looks like this in the browser:

If you are wondering what 4rem is, it’s a unit of measurement. It’s the same as 64 pixels, because 16px makes 1rem unless you change the root font-size ( html ) to another value.

To change the color of the text, you can use the style attribute, and then set a value with the color property:

text-color

This is what we now have in the browser:

Combining the font-size and color properties gives us this in the browser:

inline-text-size-and-color

How to Change Text Size and Text Color in an External CSS File

You can also change the color and size of text in an external stylesheet. Most importantly, you have to link the external CSS in the head section of your HTML.

The basic syntax for doing it looks like this:

Now, to change the text size and color of the freeCodeCamp text, you need to select it in the stylesheet and apply the appropriate properties and values to it.

Remember this is our simple HTML code:

You can change the color and size of the text by selecting the element (h1) and assigning values to the color and font-size properties:

external-text-size-and-color

We have the same result in the browser:

Conclusion

I hope this tutorial gives you the knowledge to be able to change the size and color of your HTML text so you can make them look better.

Thank you for reading, and keep coding.

Источник

Читайте также:  Цикл на убывание питон
Оцените статью