Краткое руководство по единицам измерения в css

rem

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


Вот, мы задали контейнера div . Это в 1.2 раза больше, чем любой заданный размер шрифтп, в этом случае 14px. Результат – .

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

Когда в некоторых случаях это может быть необходимо, довольно часто хочется, чтобы значение, от которого отталкивается единица измерения, было одним. В такой ситуации подойдет . Буква «r» в означает root (корень); то есть размер шрифта задается относительно корневого элемента; в большинстве случаев это будет элемент.

В каждом из трех вложенных элементов в прошлом примере, шрифт будет равен .

Удобно в случае с сетками.

Rem удобно использовать не только для установки размера шрифта. Например, вы можете задать размер шрифта целой сетке используя , обращаясь к в некоторых местах. Это даст вам более предсказуемое масштабирование.

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

The Effect of Inheritance on em Units

Working with units can start to get tricky when it comes to inheritance, because every element automatically inherits the font size of its parent. The effect of inheritance can only be overridden by explicitly setting a font size with a unit not subject to inheritance, such as or .

The font size of the element on which units are used determines their size. But that element may have inherited a font size from its parent, which inherited a font size from its parent, and so on. As such it’s possible for any value to be effected by the font size of any of its parents.

Let’s look at an example. Feel free to try this out in CodePen for yourself as we step through it. As you go along, use Chrome Developer Tools or Firebug for Firefox to inspect the pixel values our units are computed into.

Example of Inheritance

If we have a page with a root font size of (usually the default) and a child div inside it with padding of , that div will inherit the font size of from the root element. Hence its padding will translate to , i.e. 1.5 x 16 = 24.

Then what if we wrap another div around the first and set its to ?

Our wrapper div inherits the root font size of and multiplies that by its own setting of . This sets the div to have a font size of , i.e. 1.25 x 16 = 20.

Now our original div is no longer inheriting directly from the root element, instead it’s inheriting a font size of from its new parent div. Its padding value of now equates to , i.e. 1.5 x 20 = 30.

This scaling effect can be compounded even further if we add an based font size to our original div, let’s say .

The div inherits the font size from its parent, then multiplies that by its own setting, giving it a new font size of , i.e. 1.2 x 20 = 24.

The padding on our div will now change in size again with the new font size, this time to , i.e. 1.5 x 24 = 36.

Finally, to further illustrate that units are relative to the font size of the element they’re used on, (not the parent element), let’s see what happens to our padding of if we explicitly set the div to use a font size of , a value not subject to inheritance.

Now, our padding has dropped down to 21px, i.e. 1.5 x 14 = 21. It is unaffected by the font size of the parent element.

With all this potential for complication, you can see why its important to know how to use units in a manageable way.

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-sizingbreak-afterbreak-beforebreak-insidecaption-sidecaret-color@charsetclearclipclip-pathcolorcolumn-countcolumn-fillcolumn-gapcolumn-rulecolumn-rule-colorcolumn-rule-stylecolumn-rule-widthcolumn-spancolumn-widthcolumnscontentcounter-incrementcounter-resetcursordirectiondisplayempty-cellsfilterflexflex-basisflex-directionflex-flowflex-growflex-shrinkflex-wrapfloatfont@font-facefont-familyfont-feature-settingsfont-kerningfont-sizefont-size-adjustfont-stretchfont-stylefont-variantfont-variant-capsfont-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-widthmix-blend-modeobject-fitobject-positionopacityorderoutlineoutline-coloroutline-offsetoutline-styleoutline-widthoverflowoverflow-xoverflow-ypaddingpadding-bottompadding-leftpadding-rightpadding-toppage-break-afterpage-break-beforepage-break-insideperspectiveperspective-originpointer-eventspositionquotesresizerightscroll-behaviortab-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-wrapwriting-modez-index

CSS Свойства

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@charsetclearclipclip-pathcolorcolumn-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-widthmix-blend-modeobject-fitobject-positionopacityorderoutlineoutline-coloroutline-offsetoutline-styleoutline-widthoverflowoverflow-xoverflow-ypaddingpadding-bottompadding-leftpadding-rightpadding-toppage-break-afterpage-break-beforepage-break-insideperspectiveperspective-originpointer-eventspositionquotesresizerightscroll-behaviortab-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-wrapwriting-modez-index

The Effect of Browser Settings on the HTML Element Font Size

By default browsers usually have a font size of 16px, but this can be changed to anywhere from 9px to 72px by the user.

Important to Know:

The root element inherits its font size from the settings in the browser, unless overridden with an explicitly set fixed value.


So while the font size on the element is what directly determines values, that font size may have first come from browser settings.

Thus browser font size settings can effect the value of every unit used in a design, as well as every unit via inheritance.

Browser Setting Effect When No HTML Font Size is Set

Unless overridden, the element it will inherit whatever the default font size setting in the browser is. For example, let’s take a site where no property is set on the element.

If a user has their browser at the default font size of 16px, the root font size will be 16px. In Chrome Developer Tools you can see what an element has inherited by checking Show inherited properties under the Computed tab.

In this case equates to , i.e. 10 x 16 = 160.

If the user bumps their browser font size up to 18px, the root font size becomes 18px. Now translates to , i.e. 10 x 18 = 180.

Browser Setting Effect with Unit HTML Font Size

When an based font size is set on the element, the pixel value it translates to will be a multiple of the browser font size setting.

For example, if the site’s element had a property set to , the root font size would be 1.25 times the browser font size setting.

If the browser font size was set to , the root font size would come out as , i.e. 1.25 x 16 = 20.

In this case would equal , i.e. 10 x 20 = 200.

However, if the browser font size was set to , the root font size would instead translate to , i.e. 1.25 x 20 = 25.

Now would equal , i.e. 10 x 25 = 250.

CSS Tutorial

CSS HOMECSS IntroductionCSS SyntaxCSS SelectorsCSS How ToCSS CommentsCSS Colors Colors RGB HEX HSL

CSS Backgrounds Background Color Background Image Background Repeat Background Attachment Background Shorthand

CSS Borders Borders Border Width Border Color Border Sides Border Shorthand Rounded Borders

CSS Margins Margins Margin Collapse

CSS PaddingCSS Height/WidthCSS Box ModelCSS Outline Outline Outline Width Outline Color Outline Shorthand Outline Offset

CSS Text Text Color Text Alignment Text Decoration Text Transformation Text Spacing Text Shadow

CSS Fonts Font Family Font Style Font Size Font Google Font Shorthand

CSS IconsCSS LinksCSS ListsCSS TablesCSS DisplayCSS Max-widthCSS PositionCSS OverflowCSS Float Float Clear Float Examples

CSS Inline-blockCSS AlignCSS CombinatorsCSS Pseudo-classCSS Pseudo-elementCSS OpacityCSS Navigation Bar Navbar Vertical Navbar Horizontal Navbar

CSS DropdownsCSS Image GalleryCSS Image SpritesCSS Attr SelectorsCSS FormsCSS CountersCSS Website LayoutCSS UnitsCSS Specificity

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.

Components on a Grid

Before we move on, let’s combine the header and paragraph elements together into a component:

The basic styles for this component are:

So far so good. This was everything we covered in the earlier sections.

Moving on, this component can be found in differents of a website. Potential areas include:

  1. The main content area
  2. The sidebar
  3. In a 1/3 grid layout

Possible locations of the component

The header element might be rendered with a smaller when the component is placed in a narrow location, like the sidebar.

We can create a variant for this by modifying the component’s class. The markup would look like this:

And the style for this variant is:

Now, on to the component’s styles. The same two rules still apply:

  1. Size in if property should scale according to it’s
  2. Size everything else in .

As with the header element, you can identify which properties to size in by seeing if they interact with the rest of the page. There are two different ways to think about building this component:

  1. Properties of all inner elements scale with the component’s .
  2. Properties of some inner elements scale with the component’s .

Let’s build the component in both ways and you’ll see what I mean.

Conclusion

We end here our encounter with CSS rem units. It is obvious that there are many advantages in using these units in our code, like responsiveness, scalability, improved reading experience, and greater flexibility in defining components. Rem units not a universal silver bullet solution but, with careful deployment, they can solve many problems that have irked developers for years. It’s up to each one of us to unlock the full potential of rems. Start your editors, experiment and share your results with the rest of us.

For more on CSS sizing units, see:

  • A Look at Length Units in CSS
  • The New CSS3 Relative Font Sizing Units
  • The Power of em Units in CSS

Трюк с пользовательскими свойствами CSS

Пользовательские свойства CSS и несколько строк JavaScript могут стать идеальным способом получить согласованный и правильный размер вьюпорта.

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

Назовем переменную —vh. Применить ее можно следующим образом:

CSS

.my-element { height: 100vh; /* фолбэк для браузеров, которые не поддерживают пользовательские свойства */ height: calc(var(—vh, 1vh) * 100); }

1 2 3 4 5 6

.my-element {

height100vh;/* фолбэк для браузеров, которые не поддерживают пользовательские свойства */

heightcalc(var(—vh,1vh)*100);

}  

Теперь нужно внутреннюю высоту окна просмотра в JavaScript:

JavaScript

// Сначала получаем высоту окна просмотра // и умножаем ее на 1% let vh = window.innerHeight * 0.01;

// Затем устанавливаем значение свойства —vh // для корневого элемента document.documentElement.style.setProperty(‘—vh’, `${vh}px`);

1 2 3 4 5 6 7 8 9

  // Сначала получаем высоту окна просмотра // и умножаем ее на 1%

let vh=window.innerHeight*0.01;

  // Затем устанавливаем значение свойства —vh // для корневого элемента

document.documentElement.style.setProperty(‘—vh’,`${vh}px`);

 

Итак, с помощью JS мы получили высоту вьюпорта, вычислили 1% от нее и присвоили в пользовательскую переменную.

Теперь можно использовать вместо :

See the Pen Viewport Height on Mobile (no resize on update) by CSS-Tricks (@css-tricks) on CodePen.


С этим читают