Как убрать жирность текста в css
Свойства текста
Свойства шрифта
Изменение начертания шрифта и его размера происходит через свойства CSS, которые описаны в табл. 1.
Свойство | Значение | Описание | Пример |
---|---|---|---|
font-family | имя шрифта | Задает список шрифтов | P |
font-style | normal italic oblique | Нормальный шрифт Курсив Наклонный шрифт | P |
font-variant | normal small-caps | Капитель (особые прописные буквы) | P |
font-weight | normal lighter bold bolder 100–900 | Нормальная жирность Светлое начертание Полужирный Жирный 100 — светлый шрифт, 900 — самый жирный | P |
font-size | normal pt px % | нормальный размер пункты пикселы проценты | font-size: normal font-size: 12pt font-size: 12px font-size: 120% |
В примере 1 показано использование параметров при работе со шрифтами.
Пример 1. Задание свойств шрифта с помощью CSS
Ниже приведен результат данного примера (рис. 1).
Рис. 1. Вид текста после применения стилей
В табл. 2 приведены некоторые стилевые параметры для работы с текстом и результат их применения.
Пример | Пример | Пример | Пример | Пример |
font-family: Verdana, sans-serif; font-size: 120%; font-weight: light | font-size: large; font-weight: bold | font-family: Arial, sans-serif; font-size: x-small; font-weight: bold | font-variant: small-caps | font-style: italic; font-weight: bold |
Свойства текста
Кроме изменения параметров шрифтов, можно управлять и свойствами всего текста. Значения свойств приведены в табл. 3.
Свойство | Значение | Описание | Пример |
---|---|---|---|
line-height | normal множитель значение % | Интерлиньяж (межстрочный интервал) | line-height: normal line-height: 1.5 line-height: 12px line-height: 120% |
text-decoration | none underline overline line-through blink | Убрать все оформление Подчеркивание Линия над текстом Перечеркивание Мигание текста | text-decoration: none |
text-transform | none capitalize uppercase lowercase | Убрать все эффекты Начинать С Прописных ВСЕ ПРОПИСНЫЕ все строчные | text-transform: capitalize |
text-align | left right center justify | Выравнивание текста | text-align: justify |
text-indent | значение % | Отступ первой строки | text-indent: 15px; text-indent: 10% |
Ниже, в табл. 4 приведены некоторые параметры текста и результат их применения.
font-weight
Internet Explorer | Chrome | Opera | Safari | Firefox | Android | iOS |
6.0+ | 1.0+ | 3.5+ | 1.0+ | 1.0+ | 1.0+ | 1.0+ |
Краткая информация
Значение по умолчанию | normal |
---|---|
Наследуется | Да |
Применяется | Ко всем элементам |
Ссылка на спецификацию | http://www.w3.org/TR/CSS21/fonts.html#propdef-font-weight |
Версии CSS
Описание
Устанавливает насыщенность шрифта. Значение устанавливается от 100 до 900 с шагом 100. Сверхсветлое начертание, которое может отобразить браузер, имеет значение 100, а сверхжирное — 900. Нормальное начертание шрифта (которое установлено по умолчанию) эквивалентно 400, стандартный полужирный текст — значению 700.
Синтаксис
Значения
Насыщенность шрифта задаётся с помощью ключевых слов: bold — полужирное начертание, normal — нормальное начертание. Также допустимо использовать условные единицы от 100 до 900. Значения bolder и lighter изменяют жирность относительно насыщенности родителя, соответственно, в большую и меньшую сторону.
HTML5 CSS2.1 IE Cr Op Sa Fx
Результат данного примера показан на рис. 1.
Рис. 1. Применение свойства font-weight
Объектная модель
[window.]document.getElementById(» elementID «).style.fontWeight
Браузеры
font-weight
Устанавливает насыщенность шрифта. Значение указывается в виде чисел от 100 до 900 с шагом 100 или с помощью заданных ключевых слов.
Краткая информация
Значение по умолчанию | normal |
---|---|
Наследуется | Да |
Применяется | Ко всем элементам |
Анимируется | Да |
Синтаксис
Обозначения
Описание | Пример | |
---|---|---|
Указывает тип значения. | ||
A && B | Значения должны выводиться в указанном порядке. | && |
A | B | Указывает, что надо выбрать только одно значение из предложенных (A или B). | normal | small-caps |
A || B | Каждое значение может использоваться самостоятельно или совместно с другими в произвольном порядке. | width || count |
[ ] | Группирует значения. | [ crop || cross ] |
* | Повторять ноль или больше раз. | [, ]* |
+ | Повторять один или больше раз. | + |
? | Указанный тип, слово или группа не является обязательным. | inset? |
Повторять не менее A, но не более B раз. | ||
# | Повторять один или больше раз через запятую. | # |
Значения
Насыщенность шрифта задаётся с помощью ключевых слов: bold — жирное начертание и normal — нормальное начертание. Также допустимо использовать условные единицы от 100 до 900. Значения bolder и lighter изменяют жирность относительно насыщенности родителя, соответственно, в большую и меньшую сторону.
Вот как числовые значения влияют на насыщенность шрифта.
Учтите, что не все шрифты поддерживают этот набор. Если указанное значение не поддерживается, то браузер приведёт шрифт к ближайшей насыщенности. К примеру, если вы указали 900 и оно не может быть показано, то браузер в действительности применит значение 700 как ближайшее, которое работает корректно.
Основы стилизирования текста и шрифта
В данной статье мы начнём путь к овладению стилизацией текста при помощи CSS. Мы подробно изучим основы стилизации текста и шрифта, такие как толщина, начертание, семейство, стенография, выравнивание текста и другие эффекты, а также рассмотрим междустрочный и межбуквенный интервалы.
Необходимые знания: | Базовые компьютерные знания, Основы HTML (раздел Введение в HTML), основы CSS (раздел Введение в CSS). |
---|---|
Задача: | Изучить основные свойства и техники, необходимые для стилизации текста на веб-страницах. |
Что участвует в стилизации текста в CSS?
Примечание: если приведённый выше абзац оставляет вас в замешательстве, то не имеет значения — вернитесь и просмотрите нашу статью о модели коробки, чтобы освежить теорию модели коробки, прежде чем продолжить.
Свойства CSS, используемые для стилизации текста, обычно делятся на две категории, которые мы рассмотрим отдельно в этой статье:
Примечание: имейте в виду, что текст внутри элемента все затронуты как одна единая сущность. Вы не можете выбирать и стилизовать подразделы текста, если вы не обернёте их в соответствующий элемент (например, или ), или использовать текстовый псевдоэлемент, такой как ::first-letter (выделяет первую букву текста элемента). first-line (выделяет первую строку текста элемента) или ::selection (выделяет текст, выделенный в данный момент курсором.)
Шрифты
Давайте сразу перейдём к рассмотрению свойств для стилизации шрифтов. В этом примере мы применим некоторые различные свойства CSS к одному и тому же образцу HTML, который выглядит следующим образом:
Color
The color (en-US) 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 (en-US) property).
color can accept any CSS color unit, for example:
This will cause the paragraphs to become red, rather than the standard browser default black, like so:
Font families
To set a different font on 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 be discussing this in a separate article later on in the module.
Default fonts
The five names are defined as follows:
Term | Definition | Example |
---|---|---|
serif | Fonts that have serifs (the flourishes and other small details you see at the ends of the strokes in some typefaces) | My big red elephant |
sans-serif | Fonts that don’t have serifs. | My big red elephant |
monospace | Fonts where every character has the same width, typically used in code listings. | My big red elephant |
cursive | Fonts that are intended to emulate handwriting, with flowing, connected strokes. | My big red elephant |
fantasy | Fonts that are intended to be decorative. | My big red elephant |
Font stacks
Since you can’t guarantee the availability of the fonts you want to use on your webpages (even a web font could fail for some reason), you can supply a font stack so that the browser has multiple fonts it can choose from. This simply involves a font-family value consisting of multiple font names separated by commas, e.g.
In such a case, the browser starts at the beginning of the list and looks to see if that font is available on the machine. If it is, it applies that font to the selected elements. If not, it moves on to the next font, and so on.
It is a good idea to provide a suitable generic font name at the end of the stack so that if none of the listed fonts are available, the browser can at least provide something approximately suitable. To emphasise this point, paragraphs are given the browser’s default serif font if no other option is available — which is usually Times New Roman — this is no good for a sans-serif font!
A font-family example
Let’s add to our previous example, giving the paragraphs a sans-serif font:
This gives us the following result:
Font size
In our previous module’s CSS values and units article, we reviewed length and size units. Font size (set with the font-size property) can take values measured in most of these units (and others, such as percentages), however the most common units you’ll use to size text are:
A simple sizing example
Our new result is like so:
Font style, font weight, text transform, and text decoration
CSS provides four common properties to alter the visual weight/emphasis of text:
Let’s look at adding a couple of these properties to our example:
Our new result is like so:
Text drop shadows
You can apply drop shadows to your text using the text-shadow property. This takes up to four values, as shown in the example below:
The four properties are as follows:
Multiple shadows
You can apply multiple shadows to the same text by including multiple shadow values separated by commas, for example:
If we applied this to the
(en-US) element in our Tommy the cat example, we’d end up with this:
Note: You can see more interesting examples of text-shadow usage in the Sitepoint article Moonlighting with CSS text-shadow.
Text layout
With basic font properties out the way, let’s now have a look at properties we can use to affect text layout.
Text alignment
The text-align property is used to control how text is aligned within its containing content box. The available values are as follows, and work in pretty much the same way as they do in a regular word processor application:
If we applied text-align: center; to the
(en-US) in our example, we’d end up with this:
Line height
Applying this to the
elements in our example would give us this result:
Letter and word spacing
The letter-spacing and word-spacing properties allow you to set the spacing between letters and words in your text. You won’t use these very often, but might find a use for them to get a certain look, or to improve the legibility of a particularly dense font. They can take most length and size units.
So as an example, we could apply some word- and letter-spacing to the first line of each
element in our example:
Let’s add some to our example, like so:
Other properties worth looking at
The above properties give you an idea of how to start styling text on a webpage, but there are many more properties you could use. We just wanted to cover the most important ones here. Once you’ve become used to using the above, you should also explore the following:
Text layout styles:
Font shorthand
Among all those properties, only font-size and font-family are required when using the font shorthand property.
A forward slash has to be put in between the font-size and line-height properties.
A full example would look like this:
Active learning: Playing with styling text
In this active learning session, we don’t have any specific exercises for you to do: we’d just like you to have a good play with some font/text layout properties, and see what you can produce! You can either do this using offline HTML/CSS files, or enter your code into the live editable example below.
If you make a mistake, you can always reset it using the Reset button.
Test your skills!
You’ve reached the end of this article, and already did some skill testing in our Active Learning section, but can you remember the most important information going forward? You can find an assessment to verify that you’ve retained this information at the end of the module — see Typesetting a community school homepage.
This assessment tests all the knowledge discussed in this module, so you might want to read the other articles before moving on to it.
Summary
We hoped you enjoyed playing with text in this article! The next article will give you all you need to know about styling HTML lists.
Начертание
Существует несколько видов начертаний шрифта, которые встречаются на сайтах: нормальное, жирное, курсивное, подчёркнутое, перечёркнутое и выворотное (рис. 1). Все указанные вариации шрифта составляют его гарнитуру.
Рис. 1. Разное начертание шрифта текста
Большая часть начертаний в той или иной мере встречается в различных текстовых редакторах и допускает смешивание с другими. Например, можно сразу установить жирный курсивный текст. Что касается выворотки, то здесь светлый текст выводится на тёмном фоне. Для больших объёмов подобный текст (светлые буквы на тёмном фоне) читать труднее, чем в традиционном исполнении, поэтому выворотка обычно применяется для привлечения внимания читателя к тексту, например заголовку.
Чтобы управлять форматированием текста, в частности изменять начертание шрифта, можно воспользоваться для этого специальными элементами HTML или обратиться к стилям. В табл. 1 перечислены основные элементы, которые применяются для изменения оформления текста.
Код HTML | Описание |
---|---|
Текст | Определяет жирное начертание текста. |
Текст | Сильное выделение текста. Визуально не отличается от . |
Текст | Устанавливает курсивное начертание текста. |
Текст | Выделение текста. Визуально не отличается от . |
Текст | Воспроизводит текст как верхний индекс. Шрифт при этом отображается выше базовой линии текста и уменьшенного размера. |
Текст | Отображает шрифт в виде нижнего индекса. Текст при этом располагается ниже базовой линии остальных символов строки и уменьшенного размера. |
Подчёркивание текста
Хотя подчёркивание текста лучше использовать только в ссылках, правильное его применение может придать эстетичный вид элементам веб- страницы.
Вначале разберёмся, почему к подчёркиванию создалось такое отношение, чтобы не повторять чужих ошибок.
Получается, что если включить подчёркивание, то оно должно быть либо декоративным, чтобы не возникала ассоциация со ссылками, либо применяться для небольших текстов, например заголовков. Но и в этом случае текст должен оставаться самим собой и не восприниматься как ссылка.
Пример 1. Свойство text-decoration