Содержание
Set Font Size With Em
To allow users to resize the text (in the browser menu), many developers use em instead of pixels.
The em size unit is recommended by the W3C.
1em is equal to the current font size. The default text size in browsers is 16px. So, the default size of 1em is 16px.
The size can be calculated from pixels to em using this formula: pixels/16=em
Example
h1 { font-size: 2.5em; /* 40px/16=2.5em */}h2 { font-size: 1.875em; /* 30px/16=1.875em */ }p { font-size: 0.875em; /* 14px/16=0.875em */}
In the example above, the text size in em is the same as the previous example in pixels. However, with the em size, it is possible to adjust the text size in all browsers.
Unfortunately, there is still a problem with older versions of Internet Explorer. The text becomes larger than it should when made larger, and smaller than it should when made smaller.
Font Size — Размер шрифта
Свойство устанавливает размер текста.
Возможность управлять размером текста важна в веб-дизайне. Однако не следует использовать настройки размера шрифта, чтобы параграфы выглядели как заголовки или заголовки выглядели как параграфы.
Всегда используйте правильные теги HTML, такие как <h1> — <h6> для заголовков и <p> для параграфов.
Значение размера шрифта может быть абсолютным или относительным размером.
Абсолютный размер:
- Устанавливает текст в указанный размер
- Не позволяет пользователю изменять размер текста во всех браузерах (плохо по причинам доступности)
- Абсолютный размер полезен, когда известен физический размер выходных данных.
Относительный размер:
- Устанавливает размер относительно окружающих элементов
- Позволяет пользователю изменять размер текста в браузерах
Примечание: Если вы не укажете размер шрифта, размер по умолчанию для обычного текста, например параграфов, будет 16px (16px=1em).
CSS Reference
CSS ReferenceCSS Browser SupportCSS SelectorsCSS FunctionsCSS Reference AuralCSS Web Safe FontsCSS AnimatableCSS UnitsCSS PX-EM ConverterCSS ColorsCSS Color ValuesCSS Default ValuesCSS Entities
CSS Properties
align-content align-items align-self all animation animation-delay animation-direction animation-duration animation-fill-mode animation-iteration-count animation-name animation-play-state animation-timing-function
backface-visibility background background-attachment background-blend-mode background-clip background-color background-image background-origin background-position background-repeat background-size border border-bottom border-bottom-color border-bottom-left-radius border-bottom-right-radius border-bottom-style border-bottom-width border-collapse border-color border-image border-image-outset border-image-repeat border-image-slice border-image-source border-image-width border-left border-left-color border-left-style border-left-width border-radius border-right border-right-color border-right-style border-right-width border-spacing border-style border-top border-top-color border-top-left-radius border-top-right-radius border-top-style border-top-width border-width bottom box-decoration-break box-shadow box-sizing break-after break-before break-inside
caption-side caret-color @charset clear clip clip-path color column-count column-fill column-gap column-rule column-rule-color column-rule-style column-rule-width column-span column-width columns content counter-increment counter-reset cursor
direction display empty-cells filter flex flex-basis flex-direction flex-flow flex-grow flex-shrink flex-wrap float font @font-face font-family font-feature-settings font-kerning font-size font-size-adjust font-stretch font-style font-variant font-variant-caps font-weight
grid grid-area grid-auto-columns grid-auto-flow grid-auto-rows grid-column grid-column-end grid-column-gap grid-column-start grid-gap grid-row grid-row-end grid-row-gap grid-row-start grid-template grid-template-areas grid-template-columns grid-template-rows
hanging-punctuation height hyphens @import isolation justify-content @keyframes left letter-spacing
line-height list-style list-style-image list-style-position list-style-type
margin margin-bottom margin-left margin-right margin-top max-height max-width @media min-height min-width mix-blend-mode
object-fit object-position opacity order outline outline-color outline-offset outline-style outline-width overflow overflow-x overflow-y
padding padding-bottom padding-left padding-right padding-top page-break-after page-break-before page-break-inside perspective perspective-origin pointer-events position quotes
resize right
scroll-behavior
tab-size table-layout text-align text-align-last text-decoration text-decoration-color text-decoration-line text-decoration-style text-indent text-justify text-overflow text-shadow text-transform top
transform transform-origin transform-style transition transition-delay transition-duration transition-property transition-timing-function
unicode-bidi user-select
vertical-align visibility
white-space width word-break word-spacing word-wrap writing-mode
z-index
Definition and Usage
The fontFamily property sets or returns a list of font-family names and/or generic-family names for text in an element.
The browser will use the first value it recognizes.
There are two types of font-family values:
- font-family: The name of a font-family, like «verdana» or «arial»
- generic-family: The name of a generic font-family, like «serif» or «sans-serif»
Tip: Always specify a generic-family name as the last alternative!
Note: Separate each value with a comma.
Note: If a font-family name contains whitespace, it must be quoted.
Tip: Look at Web safe fonts for commonly used font combinations.
CSS Reference
CSS ReferenceCSS Browser SupportCSS SelectorsCSS FunctionsCSS Reference AuralCSS Web Safe FontsCSS AnimatableCSS UnitsCSS PX-EM ConverterCSS ColorsCSS Color ValuesCSS Default ValuesCSS Entities
CSS Properties
align-content align-items align-self all animation animation-delay animation-direction animation-duration animation-fill-mode animation-iteration-count animation-name animation-play-state animation-timing-function
backface-visibility background background-attachment background-blend-mode background-clip background-color background-image background-origin background-position background-repeat background-size border border-bottom border-bottom-color border-bottom-left-radius border-bottom-right-radius border-bottom-style border-bottom-width border-collapse border-color border-image border-image-outset border-image-repeat border-image-slice border-image-source border-image-width border-left border-left-color border-left-style border-left-width border-radius border-right border-right-color border-right-style border-right-width border-spacing border-style border-top border-top-color border-top-left-radius border-top-right-radius border-top-style border-top-width border-width bottom box-decoration-break box-shadow box-sizing break-after break-before break-inside
caption-side caret-color @charset clear clip clip-path color column-count column-fill column-gap column-rule column-rule-color column-rule-style column-rule-width column-span column-width columns content counter-increment counter-reset cursor
direction display empty-cells filter flex flex-basis flex-direction flex-flow flex-grow flex-shrink flex-wrap float font @font-face font-family font-feature-settings font-kerning font-size font-size-adjust font-stretch font-style font-variant font-variant-caps font-weight
grid grid-area grid-auto-columns grid-auto-flow grid-auto-rows grid-column grid-column-end grid-column-gap grid-column-start grid-gap grid-row grid-row-end grid-row-gap grid-row-start grid-template grid-template-areas grid-template-columns grid-template-rows
hanging-punctuation height hyphens @import isolation justify-content @keyframes left letter-spacing
line-height list-style list-style-image list-style-position list-style-type
margin margin-bottom margin-left margin-right margin-top max-height max-width @media min-height min-width mix-blend-mode
object-fit object-position opacity order outline outline-color outline-offset outline-style outline-width overflow overflow-x overflow-y
padding padding-bottom padding-left padding-right padding-top page-break-after page-break-before page-break-inside perspective perspective-origin pointer-events position quotes
resize right
scroll-behavior
tab-size table-layout text-align text-align-last text-decoration text-decoration-color text-decoration-line text-decoration-style text-indent text-justify text-overflow text-shadow text-transform top
transform transform-origin transform-style transition transition-delay transition-duration transition-property transition-timing-function
unicode-bidi user-select
vertical-align visibility
white-space width word-break word-spacing word-wrap writing-mode
z-index
15.7 Font size: the ‘font-size’ property
- ‘font-size’
-
Value: | | | | Initial: medium Applies to: all elements Inherited: yes Percentages: refer to inherited font size Media: Computed value: absolute length
The font size corresponds to the em square, a concept used in typography. Note that certain glyphs may bleed outside their em squares. Values have the following meanings:
- <absolute-size>
- An <absolute-size> keyword is an index to a table of font
sizes computed and kept by the UA. Possible values are:
The following table provides user agent guidelines for the absolute-size mapping to HTML heading and absolute font-sizes. The ‘medium’ value is the user’s preferred font size and is used as the reference middle value.
CSS absolute-size values xx-small x-small small medium large x-large xx-large HTML font sizes 1 2 3 4 5 6 7 Implementors should build a table of scaling factors for absolute-size keywords relative to the ‘medium’ font size and the particular device and its characteristics (e.g., the resolution of the device).
Different media may need different scaling factors. Also, the UA should take the quality and availability of fonts into account when computing the table. The table may be different from one font family to another.
Note 1. To preserve readability, a UA applying these guidelines should nevertheless avoid creating font-size resulting in less than 9 pixels per EM unit on a computer display.
Note 2. In CSS1, the suggested scaling factor between adjacent indexes was 1.5, which user experience proved to be too large. In CSS2, the suggested scaling factor for a computer screen between adjacent indexes was 1.2, which still created issues for the small sizes. Implementation experience has demonstrated that a fixed ratio between adjacent absolute-size keywords is problematic, and this specification does not recommend such a fixed ratio.
- <relative-size>
- A <relative-size> keyword is interpreted relative to the table of font sizes and the font size of the parent element. Possible values are: . For example, if the parent element has a font size of ‘medium’, a value of ‘larger’ will make the font size of the current element be ‘large’. If the parent element’s size is not close to a table entry, the UA is free to interpolate between table entries or round off to the closest one. The UA may have to extrapolate table values if the numerical value goes beyond the keywords.
Length and percentage values should not take the font size table into account when calculating the font size of the element.
Negative values are not allowed.
On all other properties, ’em’ and ‘ex’ length values refer to the computed font size of the current element. On the ‘font-size’ property, these length units refer to the computed font size of the parent element.
Note that an application may reinterpret an explicit size, depending on the context. E.g., inside a VR scene a font may get a different size because of perspective distortion.
Examples:
p { font-size: 16px; } @media print { p { font-size: 12pt; } } blockquote { font-size: larger } em { font-size: 150% } em { font-size: 1.5em }
Семейство шрифтов — Serif, Sans-Serif, Monospace, Script, Fantasy
Одним из самых простых способов воздействовать на дизайн веб-страницы являются шрифты, которые вы используете. Данное руководство поможет вам найти шрифт, который лучше всего подходит для вашей ситуации.
Некоторые правила 1.Не использовать более 3-4 шрифтов на одной странице. 2.Не изменить шрифт в середине предложения, пока у вас нет очень веских оснований. 3.Sans-Serif для онлайн версии, Serif для печати. 4.Monospace для пишущей машинки и кодов. 5.Script и fantasy для важных штрихов.
Sans-serif шрифты являются основой Вашего Сайта Sans-serif это те шрифты, которые не имеют «засечки»: маленькие крючки в конце письма. Если у вас были какие-либо курсы дизайна печати, вероятно, было сказано, что вы должны использовать только sans-serif для заголовок. Это не относится к Интернету. Веб-страницы предназначены для просмотра веб-браузерами, на компьютерных мониторах. И компьютерные мониторы не имеют такую же хорошую резолюцию, как бумага. Это означает, что когда ваши читатели смотрят страницу с serif шрифтами на экране, маленькие засечки делают текст трудным для чтения.
Всегда используйте sans-serif для основной копии Вашей веб-страницы.
Некоторые примеры шрифтов без засечек (sans-serif):
•Arial •Geneva •Helvetica •Lucida Sans •Trebuchet •Verdana Verdana это семейство шрифтов, который фактически был изобретен для использования в Интернете.
Использование Serif шрифтов для печати Хотя Serif шрифты трудно прочитать онлайн, они идеально подходят для печати.
Некоторые примеры Serif шрифтов:
•Garamond •Georgia •New York •Times •Times New Roman Monospace используется для примеров кода Даже если ваш сайт не о вычислительной технике, вы можете использовать monospace, чтобы предоставить инструкции, приводить примеры или показать машинописный текст. Monospace буквы имеют одинаковую ширину для каждого символа, поэтому они всегда занимают одинаковое место на странице. Пишущие машинки обычно использовали monospace шрифты.
Некоторые примеры monospace шрифтов:
•Courier •Courier New •Lucida Console •Monaco Не используйте Fantasy или Cursive для основного текста (body text)
Используйте fantasy и cursive шрифты в изображениях и заголовках.
Некоторые примеры fantasy шрифтов:
•Copperplate •Desdemona •Impact •Kino
Некоторые примеры рукописных шрифтов:
•Comic Sans MS •Lucida Handwriting •Zapf Chancery
JavaScript
JS Array concat() constructor copyWithin() entries() every() fill() filter() find() findIndex() forEach() from() includes() indexOf() isArray() join() keys() length lastIndexOf() map() pop() prototype push() reduce() reduceRight() reverse() shift() slice() some() sort() splice() toString() unshift() valueOf()
JS Boolean constructor prototype toString() valueOf()
JS Classes constructor() extends static super
JS Date constructor getDate() getDay() getFullYear() getHours() getMilliseconds() getMinutes() getMonth() getSeconds() getTime() getTimezoneOffset() getUTCDate() getUTCDay() getUTCFullYear() getUTCHours() getUTCMilliseconds() getUTCMinutes() getUTCMonth() getUTCSeconds() now() parse() prototype setDate() setFullYear() setHours() setMilliseconds() setMinutes() setMonth() setSeconds() setTime() setUTCDate() setUTCFullYear() setUTCHours() setUTCMilliseconds() setUTCMinutes() setUTCMonth() setUTCSeconds() toDateString() toISOString() toJSON() toLocaleDateString() toLocaleTimeString() toLocaleString() toString() toTimeString() toUTCString() UTC() valueOf()
JS Error name message
JS Global decodeURI() decodeURIComponent() encodeURI() encodeURIComponent() escape() eval() Infinity isFinite() isNaN() NaN Number() parseFloat() parseInt() String() undefined unescape()
JS JSON parse() stringify()
JS Math abs() acos() acosh() asin() asinh() atan() atan2() atanh() cbrt() ceil() cos() cosh() E exp() floor() LN2 LN10 log() LOG2E LOG10E max() min() PI pow() random() round() sin() sqrt() SQRT1_2 SQRT2 tan() tanh() trunc()
JS Number constructor isFinite() isInteger() isNaN() isSafeInteger() MAX_VALUE MIN_VALUE NEGATIVE_INFINITY NaN POSITIVE_INFINITY prototype toExponential() toFixed() toLocaleString() toPrecision() toString() valueOf()
JS OperatorsJS RegExp constructor compile() exec() g global i ignoreCase lastIndex m multiline n+ n* n? n{X} n{X,Y} n{X,} n$ ^n ?=n ?!n source test() toString() (x|y) . \w \W \d \D \s \S \b \B \0 \n \f \r \t \v \xxx \xdd \uxxxx
JS Statements break class continue debugger do…while for for…in for…of function if…else return switch throw try…catch var while
JS String charAt() charCodeAt() concat() constructor endsWith() fromCharCode() includes() indexOf() lastIndexOf() length localeCompare() match() prototype repeat() replace() search() slice() split() startsWith() substr() substring() toLocaleLowerCase() toLocaleUpperCase() toLowerCase() toString() toUpperCase() trim() valueOf()
С этим читают
- :first-child
- Background-color
- Css 3d transforms
- How to add border to html table
- Css свойство padding-top
- Border-image
- Animated gifs, animated images & animations
- Свойство background: все настройки фона в одном месте
- Применение псевдоклассов в css для выборки элементов
- Background-position: позиционирование фона