Rem in css: understanding and using rem units

Содержание:

Что такое em?

В CSS единица измерения em равна текущему размеру шрифта элемента, к которому применяется em. Когда единицы измерения em используются в дочерних элементах, которые не имеют определенного размера шрифта, они наследуют его от родителей, вплоть до корневого элемента документа.

Посмотрите на следующий код CSS:

.example {
    font-size: 20px;
}

В данном случае 1em этого элемента или его дочерних элементов (при отсутствии других определений font-size) будет равен 20px. Так что, если мы добавим строку:

.example {
    font-size: 20px;
    border-radius: .5em;
}

Значение border-radius равное 5em будет равно 10px (то есть 20 * 0,5). Аналогично:

.example {
    font-size: 20px;
    border-radius: .5em;
    padding: 2em;
}

Значение отступа 2em будет равно 40px (20 * 2). Как уже упоминалось, этот тип вычислений применяется к любым дочернему элементу, если у него нет явно определенного размера шрифта. Тогда величина единицы измерения em в CSS будет вычислена подобным образом.

Если в CSS размер шрифта не определен, то em будет равна размеру шрифта, используемого по умолчанию в браузере. Чаще всего это значение составляет 16px. Давайте рассмотрим, как можно использовать этот метод для легкого изменения размера элементов.

Проценты %

Проценты , как и – относительные единицы.

Когда мы говорим «процент», то возникает вопрос – «Процент от чего?»

Как правило, процент будет от значения свойства родителя с тем же названием, но не всегда.

Это очень важная особенность процентов, про которую, увы, часто забывают.

Отличный источник информации по этой теме – стандарт, Visual formatting model details.

Вот пример с , он выглядит в точности так же, как с :

В примере выше процент берётся от размера шрифта родителя.

А вот примеры-исключения, в которых берётся не так:

При установке свойства в , процент берётся от ширины родительского блока, а вовсе не от его .
При установке свойства в , процент берётся от текущего размера шрифта, а вовсе не от родителя. Детали по и размеру шрифта вы также можете найти в статье Свойства font-size и line-height.
Для обычно процент от ширины/высоты родителя, но при , процент берётся от ширины/высоты окна (а не родителя и не документа). Кроме того, иногда требует соблюдения дополнительных условий, за примером – обратитесь к главе Особенности свойства height в %.

Единицы изменения viewport (окно просмотра)

CSS

.element-one {
  font-size: 100vh;
}

.element-two {
  font-size: 100vw;
}
.

Viewport-единицы, такие как vw и vh, позволяют устанавливать размер шрифта относительно длины или ширины окна просмотра:

  • 1vw = 1% от ширины окна просмотра;
  • 1vh = 1% от высоты окна просмотра.

То есть, если мы посмотрим на следующий пример:

CSS

.element {
  font-size: 100vh;
}
}

то увидим, что размер текста CSS всегда должен находиться на отметке в 100% ширины окна просмотра (50vh будет означать 50%, 15vh — 15% и так далее). В приведенном ниже демо попробуйте изменить высоту, и посмотрите, как растягивается шрифт:

vw-единицы отличаются тем, что позволяют указывать высоту символов, руководствуясь шириной окна просмотра. В приведенном ниже демо вам нужно будет изменить ширину окна браузера, чтобы увидеть изменения:

Эти единицы измерения поддерживаются следующими браузерами:

Chrome Safari Firefox Opera IE Android iOS
31+ 7+ 31+ 27+ 9+ 4.4+ 7.1+

В нашем распоряжении имеются еще две единицы измерения, основанные на размере окна просмотра. Первая позволяет вычислять значения vh и vw, и устанавливать свойству font-size минимальное значение, а vmax позволяет определить и установить, наоборот, максимальное значение.

CSS Reference

CSS ReferenceCSS Browser SupportCSS SelectorsCSS FunctionsCSS Reference AuralCSS Web Safe FontsCSS Font FallbacksCSS 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

gap
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
row-gap

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

Relative Lengths

Relative length units specify a length relative to another length property.
Relative length units scales better between different rendering mediums.

Unit Описание
em Relative to the font-size of the element (2em means 2 times the size of the current font)
ex Relative to the x-height of the current font (rarely used)
ch Relative to width of the «0» (zero)
rem Relative to font-size of the root element
vw Relative to 1% of the width of the viewport*
vh Relative to 1% of the height of the viewport*
vmin Relative to 1% of viewport’s* smaller dimension
vmax Relative to 1% of viewport’s* larger dimension
% Relative to the parent element

Совет: Модули EM и REM практичны в создании идеально масштабируемой компоновки! * Видовой экран = размер окна браузера. Если видовой экран шириной 50 см, 1ВВ = 0.5 cm.

CSS-переменные облегчают разделение поведения и стиля

Реактивность переменных CSS — это делает их мощными. При правильном использовании стили могут оставаться в CSS, а вычисления — в JavaScript, где им и положено находиться. Предположим, нужен радиальный градиентный фон, на котором центральная точка градиента следует за курсором мыши. Раньше приходилось генерировать весь градиент в JavaScript и устанавливать его во встроенном (inline) стиле HTML-элемента при каждом движении мыши. С CSS-переменными в JavaScript необходимо установить только две переменные: и . В обычном JavaScript это может выглядеть так:

Затем надо в CSS настроить эффект, например, так:

See this code CSS gradient that follows the mouse with CSS variables on x.xhtml.ru.

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

See this code CSS gradients that follow the mouse with CSS variables on x.xhtml.ru.

Предположим, надо сделать, чтобы оттенки и угол в коническом градиенте менялись в зависимости от времени суток. Тот же самый JavaScript будет работать и для мыши, поэтому следует добавить немного JavaScript, который устанавливает CSS-переменную с текущим часом (0–23):

Затем включить эту переменную в CSS и использовать её в вычислениях:

See this code CSS gradient «clock» that follows the mouse with CSS on x.xhtml.ru.

Поскольку все три переменные, установленные с помощью JavaScript, являются чистыми данными, а не значениями из CSS, их можно использовать в нескольких несвязанных CSS-правилах. (Они не относятся непосредственно к эффектам только для фона.)

CSS Properties

align-contentalign-itemsalign-selfallanimationanimation-delayanimation-directionanimation-durationanimation-fill-modeanimation-iteration-countanimation-nameanimation-play-stateanimation-timing-functionbackface-visibilitybackgroundbackground-attachmentbackground-blend-modebackground-clipbackground-colorbackground-imagebackground-originbackground-positionbackground-repeatbackground-sizeborderborder-bottomborder-bottom-colorborder-bottom-left-radiusborder-bottom-right-radiusborder-bottom-styleborder-bottom-widthborder-collapseborder-colorborder-imageborder-image-outsetborder-image-repeatborder-image-sliceborder-image-sourceborder-image-widthborder-leftborder-left-colorborder-left-styleborder-left-widthborder-radiusborder-rightborder-right-colorborder-right-styleborder-right-widthborder-spacingborder-styleborder-topborder-top-colorborder-top-left-radiusborder-top-right-radiusborder-top-styleborder-top-widthborder-widthbottombox-decoration-breakbox-shadowbox-sizingcaption-sidecaret-color@charsetclearclipcolorcolumn-countcolumn-fillcolumn-gapcolumn-rulecolumn-rule-colorcolumn-rule-stylecolumn-rule-widthcolumn-spancolumn-widthcolumnscontentcounter-incrementcounter-resetcursordirectiondisplayempty-cellsfilterflexflex-basisflex-directionflex-flowflex-growflex-shrinkflex-wrapfloatfont@font-facefont-familyfont-kerningfont-sizefont-size-adjustfont-stretchfont-stylefont-variantfont-weightgridgrid-areagrid-auto-columnsgrid-auto-flowgrid-auto-rowsgrid-columngrid-column-endgrid-column-gapgrid-column-startgrid-gapgrid-rowgrid-row-endgrid-row-gapgrid-row-startgrid-templategrid-template-areasgrid-template-columnsgrid-template-rowshanging-punctuationheighthyphens@importisolationjustify-content@keyframesleftletter-spacingline-heightlist-stylelist-style-imagelist-style-positionlist-style-typemarginmargin-bottommargin-leftmargin-rightmargin-topmax-heightmax-width@mediamin-heightmin-widthobject-fitopacityorderoutlineoutline-coloroutline-offsetoutline-styleoutline-widthoverflowoverflow-xoverflow-ypaddingpadding-bottompadding-leftpadding-rightpadding-toppage-break-afterpage-break-beforepage-break-insideperspectiveperspective-originpointer-eventspositionquotesresizerighttab-sizetable-layouttext-aligntext-align-lasttext-decorationtext-decoration-colortext-decoration-linetext-decoration-styletext-indenttext-justifytext-overflowtext-shadowtext-transformtoptransformtransform-origintransform-styletransitiontransition-delaytransition-durationtransition-propertytransition-timing-functionunicode-bidiuser-selectvertical-alignvisibilitywhite-spacewidthword-breakword-spacingword-wrapz-index

Body Font Size

In the table below, select a body font size in pixels (px) to display a
complete «px to em and percent» conversion table.

Tip: The default font size is usually 16px.

What is the difference between PX, EM and Percent?

Pixel
is a static measurement, while percent and EM are relative
measurements. Percent depends on its parent font size. EM is relative to the
current font size of the element (2em means 2 times the size of the current
font). So, If the font
size of body is 16 pixels, then 150% will be 24 pixels (1.5 * 16), and 2em will
be 32 pixels (16 * 2).
Look at CSS Units for more
measurement units.

❮ Previous
Next ❯

CSS-переменные упрощают инкапсуляцию стилей

CSS-переменные позволяют повторно использовать и настраивать CSS-код, поскольку они делают возможной инкапсуляцию. Предположим, есть стиль плоской кнопки, примененный к классу . Его упрощенный CSS-код выглядит так:

Допустим, ещё нужны кнопки разного цвета для разных действий, например красная кнопка для опасного действия. Можно добавить поддержку класса-модификатора и переопределять соответствующие объявления:

Заменим цвет переменной, чтобы избежать дублирования:

Теперь всё упростилось до переопределения одного свойства: :

Можно даже создавать темы «на лету», переопределяя свойство во встроенном (inline) стиле кнопки.

Это триумф краткости, но гораздо больший триумф инкапсуляции — роскошь, которую CSS не всегда позволял своим разработчикам. Фактически, натягивание тем на сторонний CSS-код раньше означало близкое знакомство с его внутренней структурой, а изменение стороннего кода требовало аналогичных обширных изменений и в коде тем. Теперь настраиваемые CSS-свойства могут служить своего рода API: кардинально меняя базовый стиль только с помощью настраиваемых свойств.

Возвращаясь к примеру с кнопкой, предположим, что надо добавить переход для более плавного эффекта наведения. Ещё надо, чтобы новый цвет фона увеличивался внутрь от границы вместо затухания по умолчанию, которое получается при переходе между двумя цветами фона. Для этого нужно имитировать фон с помощью :

Несмотря на то, что сама реализация довольно существенно изменилась, работают все цветовые темы кнопок. Если бы было нужно переопределять CSS для создания тем, код этих тем был бы сломан.

Эта возможность — не экономия нескольких символов или времени на обслуживание, она является истинной ценностью настраиваемых свойств. Они позволяют делиться кодом, который может быть повторно использован и настроен другими разработчиками, при этом допускает полностью изменять его внутреннюю структуру. Пользовательские свойства также являются единственным способом создания компонентов shadow DOM, потому что, в отличие от любых других CSS-свойств, они выходят за пределы shadow DOM.

Why Use em Units

The key value units offer is they allow sizing values to be determined by a font size other than that of the element.

For this reason, the primary purpose of units should be to allow for scalability within the context of a specific design element.

For example, you might set the , and around a navigation menu item to use values.

Menu with 0.9rem font size

This way if you change the menu’s font size the spacing around the menu items will scale proportionately, independently of the rest of the layout.

Menu with 1.2rem font size

In the earlier section on inheritance you saw how quickly keeping track of units can get out of hand. For this reason, I recommend only using units if you identify a clear need for them.

Доступность это важно

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

Это станет проблемой для пользователей, которые полагались на зум в браузере.

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

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

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

Using Only REMs to Make a Header Element

Say you have a header element () that looks like this:

I’m a header!

The header’s styles should be similar to the following if you sized everything in :

So far so good.

Next, let’s create a slightly bigger header element since it’s common to have differently-sized elements on the same website. While doing so, let’s try to inherit as many styles as possible.

The markup of the bigger header element might be something like this:

The CSS would be:

Unfortunately, the code doesn’t turn out well. You can see that there’s too little breathing space between the edge and text of .

Not enough breathing space between edge and text on this large header

If you insist on using only s, the only way to fix this problem is to redeclare the on the large header:

More padding the large header now!

Notice the pattern here? ’s is twice as large as ’s. Consequently, on is twice as large as on .

What would happen if we have more headers of different sizes, or if the headers have to change in size? You can already see how coding the entire site in can cause duplication and super complex code.

We can simplify the code such that there’s no need to redeclare on if we don’t mind using both and :

As you can see, can be incredibly helpful when you have a property that needs to scale with it’s font size. This is where the first rule was born.

Next, let’s take a look at what happens if you use an only approach for the same header.

Practical Application

There may be some debate among web designers and I’m sure different people have different preferred approaches, however my recommendation is as follows.

Use Units For:

Any sizing that should scale depending on the font-size of an element other than the root.

Generally speaking, the only reason you’ll need to use units is to scale an element which has non default font sizing.

As per our example above, design components like menu items, buttons, and headings may have their own explicitly stated font sizes. If you change these font sizes, you want the entire component to scale proportionately.

Common properties this guideline will apply to are , , , and settings, when used on elements with non default font sizing.

I recommend that when you do employ units, the font size of the element they’re used on should be set in units to preserve scalability but avoid inheritance confusion.

Typically Don’t Use Units for Font Sizes

It’s quite common to see units used for font sizing, particularly in headings, however I would suggest that designs are more manageable if units are typically used for font sizing.

The reason headings often use units is they’re a better choice than units, being relative to regular text size. However units can achieve this goal equally well. If any font size adjustment on the element is made, the heading sizes will still scale too.

Try changing the font size on the element in this CodePen to see for yourself:

More often than not, we don’t want our font sizes to scale based on any element other than the root, with only a few exceptions.

One example where we might want based font sizing could be a drop down menu, where we have second level menu item text sized depending on the font size of the first level. Another example might be a font icon used inside a button, where the icon’s size should relate to the button’s text size.

However most elements in a web design will tend not to have this type of requirement, so you’ll generally want to use units for font sizing, with units only where specifically needed.

Use units for:

Any sizing that doesn’t need units for the reasons described above, and that should scale depending on browser font size settings.

This accounts for almost everything in a standard design including most heights, most widths, most padding, most margins, border widths, most font sizes, shadows, basically almost every part of your layout.

In a nutshell, everything that can be made scalable with units, should be.

Tip

When creating layouts it’s often easier to think in pixels but output in units.

You can have pixel to calculations done automatically via a preprocessor like Stylus / Sass / Less, or a postprocessor like PostCSS with the PXtoRem plugin.

Alternatively, you can use PXtoEM to manually do your conversions.

Always Use Media Queries

Importantly, when using units to create a uniformly scalable design, your media queries should also be in units. This will ensure that whatever a user’s browser font size, your media queries will respond to it and adjust your layout.

For example, if a user scales up text very high, your layout may need to snap down from a two columns to a single column, just as it might on a smaller screened mobile device.

If your breakpoints are at fixed pixel widths, only a different viewport size can trigger them. However with based breakpoints they will respond to different font sizing too.

Don’t Use or For:

Multi Column Layout Widths

Column widths in a layout should typically be based so they can fluidly fit unpredictably sized viewports.

However single columns should still generally incorporate values via a setting.

For example:

This keeps the column flexible and scalable, but prevents it from becoming too wide for the text therein to be comfortably readable.

When an Element Should be Strictly Unscalable

In a typical web design there won’t be many parts of your layout that can’t be designed for scalability. However occasionally you will come across elements that really do need to use explicit fixed values for the purpose of preventing scaling.

The precondition for employing fixed sizing values should be that if the element in question were scaled it would break. This really doesn’t come up often, so before you’re tempted to whip out those units, ask yourself if using them is an absolute necessity.

What are ems?

In CSS, an em unit is equal to the computed for the element to which the em is applied. When em units are declared on child elements that don’t have a defined, they will inherit their from their parent, or from another ancestor element, possibly going all the way back to the root element on the document.

Look at the following CSS:

In this case, 1em on this element, or on its child elements (assuming no other definitions), would be equal to 20px. So if we added a line:

This value of computes to 10px (i.e. 20*.5). Similarly:

The padding value of is equal to 40px (20*2). As mentioned, this type of calculation would apply to any child elements as well — unless any of those child elements had an explicitly defined value, in which case the em value would be calculated based on that. If no font size is defined anywhere in the CSS, the em unit will be equal to the browser’s default font size for the document, which is usually 16px.

I think that should make it clear how ems work. Now let’s look at how this technique can be used to make easily resizable web components, as discussed by Simurai in the original Medium article. I’ll take his idea a step further by providing a demo to see this in action.

Абсолютные ключи и значения

CSS

.element {
  font-size: small;
}
}

Свойство, которое устанавливает размер текста CSS, принимает следующие ключевые слова:

  • xx-small;
  • x-small;
  • small;
  • medium;
  • large;
  • x-large;
  • xx-large.

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

Среди других абсолютных значений можно выделить mm (миллиметры), cm (сантиметры), in (дюймы), pt (пункты) и pc (пики). Один pt равен 1/72 дюйма, или одна пика равна 12 пунктам. Обычно эти единицы используются в печатных документах.

Новые псевдоклассыСкопировать ссылку

Единицы измерения и значения — это всё прекрасно, но особенно меня радуют селекторы и псевдоклассы. Когда у меня получается выдумать замысловатый селектор, даже если он в итоге будет запрятан там, где только немногие избранные смогут его найти, я всегда чувствую себя мастером своего дела. Перефразируя отца Стива Джобса: ты должен сделать так, чтобы забор со стороны твоего дома выглядел так же хорошо, как со стороны улицы, даже если больше никто не будет знать, что это так — ведь ты будешь.

Для меня стало откровением, когда я впервые использовал , это было словно я вышиб ногой двери восприятия… Окей, я чуть-чуть преувеличиваю. Но есть несколько новых CSS-псевдоклассов, относительно которых действительно стоит испытывать энтузиазм.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *