: элемент акцентирования

Относительные длины

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

Единица Описание
em Относительно размера шрифта элемента (2em означает 2-кратный размер текущего шрифта) Попробуй
ex Относительно x-высоты текущего шрифта (редко используется) Попробуй
ch Относительно ширины «0» (нуля) Попробуй
rem Относительно размера шрифта корневого элемента Попробуй
vw Относительно 1% ширины области просмотра* Попробуй
vh Относительно 1% высоты области просмотра* Попробуй
vmin Относительно 1% меньшего размера области просмотра* Попробуй
vmax Относительно 1% большего размера области просмотра* Попробуй
% Относительно родительского элемента Попробуй

Совет: Единицы em и rem удобны в создании идеально масштабируемого макета! *Viewport = размер окна браузера. Если ширина окна составляет 50 см, 1vw = 0.5 см.

When to Use Pixels

You’re looking at a monitor which is comprised of lots of tiny dots that are used to make up an image. These are pixels. Or rather, they’re what people usually mean when they talk about pixels. Pixels (px) in CSS do not mean the same thing as pixels on your monitor —in fact, they’re a non-linear angular measurement. It doesn’t really matter what that means and it seems people like to argue about what exactly it does mean, but you do need to understand that pixels are an absolute unit of measurement. Absolute means that they are the same size regardless of the size of anything else (that will make more sense in second). In practice, they aren’t the same length everywhere because different devices treat them differently, but on each device a pixel is always the same. 16px on your laptop monitor is not the same as 16px on your iPad. Pixels are absolute but not consistent.

Абсолютная длина

Единицы абсолютной длины являются фиксированными, и длина, выраженная в любом из них, будет отображаться как именно этот размер.

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

Длина Описание
cm сантиметры
Код
mm милиметры
Код
in дюймы (1in = 96px = 2.54cm)
Код
px * пикселы (1px = 1/96th of 1in)
Код
pt точки (1pt = 1/72 of 1in)
Код
pc цицеро (1pc = 12 pt)
Код

* Пиксели (px) относительно устройства просмотра. Для устройств с низким разрешением 1px — это один пиксель (точка) дисплея. Для принтеров и высокого разрешения
экраны 1px подразумевает несколько пикселей устройства.

Интро

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

Viewport единицы это , ,  и .

Viewport ширина

Единица  представляет собой процентное измерение ширины корневого элемента. Один  равен 1% ширины вьюпорта.

Тут у нас есть элемент с таким CSS:

Когда ширина вьюпорта равна , то  будут высчитаны таким образом:

Viewport высота

Единица  представляет собой процентное измерение высоты корневого элемента. Один  равен 1% высоты вьюпорта.

У нас есть элемент с таким CSS:

Если высота вьюпорта равна , то  будет высчитано следующим образом:

Вот и всё! Теперь давайте взглянем на другие единицы.

Vmin

Эта единица является минимумом ширины или высоты вьюпорта. Если ширина вьюпорта больше его высоты, то значение единицы будет высчитано, основываясь на высоте.

Давайте посмотрим на пример ниже.

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

Вот как она будет считаться:

Как вы уже могли предположить, результат будет считаться таким образом:

Vmax

Это прямая противоположность . Значение считается основываясь на максимальной ширине и высоте.

Давайте посмотрим на пример:

Результат бы был высчитан таким образом:

ex и ch

Единицы и , по аналогии с и , соотносятся с текущим шрифтом и размером шрифта. Но, в отличие от и , они также соотносятся  c .

или character является продвинутой единицей измерения ширины от нуля, . Наиболее интересные обсуждения того, что это может значить, можно найти в блоге Эрика Мейерса. Вкратце, если мы возьмем моноширинный шрифт, контейнер с шириной из букв, тогда, например, всегда будет содержать выражение из 40 единиц этого конкретного шрифта. Когда стандартным использованием этого правила является пример шрифта Брайля, возможности творческого подхода существенно расширяют его функционал.

обозначается как «x-высота текущего шрифта ИЛИ половина «. выбранного шрифта называется высота буквы x нижнего регистра этого шрифта. Часто эта высота оказывается срединной точки всей высоты шрифта.

X-высота; высота буквы x нижнего регистра (читайте больше про структуру веб типографики)

Для этой единицы измерения существует множество вариантов использования, большинство из них являются небольшими дополнениями к основной типографике. Например, элемент , который обозначает надстрочные символы, может быть приподнят относительно своей позиции, если ему задать position: relative и значение свойства bottom 1ex. Таким же образом вы можете опустить подстрочные буквы еще ниже. Стандартные настройки браузера использует свои правила надстрочных и подстрочных символов. Но если вам нужна более тонкая настройка, вы можете сделать ее следующим образом:

Могу ли я это использовать?

Единица существует примерно , а вот для такой поддержки вы не найдете. Для ознакомления со спецификацией по поддержке свойств, ознакомьтесь со значениями и единицами CSS в блоге Эрика Мейерса.

Some Notes, Flaws, etc.

As you can see from using the range slider in the demo, this type of flexible resizing isn’t always something you’ll want to use. It can be somewhat restricting.

You may have to tweak some of the em values to get them how you like, and, as in the case of the parent border in the demo, you may not want the resize-ability to apply to all elements. You can overcome this easily by simply avoiding ems on the elements you want to leave out.

As described in the discussion on Simurai’s original article, you don’t have to use px units to set the root . You can use ems for that too, but just remember that this will be inherited in the same way from its parent, possibly coming from the document’s default value for .

Вот некоторые примеры:

Мы используем 6 знаков после запятой, поскольку некоторые браузеры не показывают никакой разницы между 2-5.d.p.

Пример 1: в браузере установлен режим масштабирования 100%, ширина браузера устанавливается на 640pх

Пример 1б: в браузере установлен режим масштабирования 100%, ширина браузера устанавливается на 639pх

Поэтому мы не можем использовать 6dp для EM, так как она попадает как медиа-запросы.

Пример 2: в браузере установлен режим масштабирования 110%, ширина браузера устанавливается на 704pх (потому что 640px * 110% = 704px)

Пример 2б: в браузере установлен режим масштабирования 110%, ширина браузера устанавливается на 705pх

Таким образом, мы не можем использовать 2dp для EM. Так что все мы остались на этом этапе является 6dp пикселей. Это работает с зумом браузера. Однако…

Пример 3: в браузере установлен режим масштабирования 100%, размер шрифта браузера 20px, ширина браузера устанавливается на 800pх (потому что 640 * 125% = 800)

Так опять же, 6dp EM все еще вне. И мы не можем использовать пиксели длямедиа запросов, потому что они по-прежнему попадают в 640px/639px, потому что они игнорируют EM/REM.

Относительные единицы

К относительным единицам измерения относятся пиксели (px) и проценты (%). Процент — единица измерения, не имеющая напрямую никакого отношения к размеру шрифта в элементе или к размеру самого элемента. Величина свойства, установленная в процентах, напрямую зависит от величины этого же свойства, установленного для родительского элемента. Например, размер шрифта задается относительно размера шрифта родительского элемента, также высота и ширина выражается в процентах относительно высоты и ширины области содержимого родительского элемента.

.one-pixel { font-size: 1px; }
.one-percent { font-size: 1%; }

Пиксель — точка равная одному физическому пикселю на экране. Однако браузеры не всегда точно расчитывают размер области просмотра в пикселях.

Рассмотрим последние модели ноутбуков, планшетов и смартфонов, оснащенные экранами с высоким разрешением. На таких устройствах браузер не соотносит единицу px с количеством физических пикселей на экране. Вместо этого он нормализует единицу px, так чтобы приблизить характеристики просмотра к традиционному настольному монитору с плотностью пикселей в районе от 96 до 120 пикселей/дюйм. В результате квадрат со стороной в 10px может отрисовыватся браузером на смартфоне так, что на каждой стороне окажется от 15 до 20 физических пикселей. Это означает, что px также оказывается относительной единицей измерения.

Component-Level Sizing

The concept of “components” is pretty popular right now. It works well with modular CSS techniques as well as with the idea of encapsulated sections of code in general. And I’m guessing the following technique will be even more interesting when the Web Components spec becomes widely supported.

The technique basically works like this: The property is used, as Simurai refers to it, as a “trojan horse”, creating the base unit for the various elements inside our component, or module. Since em units, as described above, are calculated based on the root-defined on the parent element, this makes the entire component easily resizable by simply changing the on the parent element.

Let’s look at this in action in a CodePen demo:

See the Pen Using ems for resizable components by SitePoint (@SitePoint) on CodePen.

This silly little module has four basic elements in it. Nothing fancy, just an example to illustrate this technique. Move the range slider at the top of the demo page to change the size of the module. You can also test it at full screen. The range slider is hooked onto a single value on the root element for the component: The value.

It should be noted here that the purpose of making the component resizable using this single CSS property is not necessarily so that the user can do this. It’s mainly so that the developer maintaining the module can make adjustments quickly, without fiddling with the different values in all parts of the component.

As described in the previous section, as the font size changes, this trickles down to all the em values that are set on that parent element as well as to all of its child elements, making all parts of the component proportionally flexible.

If you examine the CSS, you’ll notice the following:

  • Everything inside the component is sized with ems, except the outside border (which we want to remain at 2px at all times), and the image, which I could resize if we wanted it to, but I’m happy with its size being static for this case.
  • The teardrop-like thing in the top right corner is a pseudo-element, which likewise benefits from the base on the parent.
  • The CSS also includes two media queries that adjust the on the parent. Again, this shows the usefulness of this technique because you don’t have to change all the various sizes in the media queries, but only the .

Using Only EMs to Make a Header Element

An implementation isn’t far from the code we left off. All we have to do is change to .

Both and will look exactly the same as their counterparts.

Is that it?

Nope!

It’s highly unlikely that your website contains only one header element. We have to consider how this header interacts with other elements on your page.

It’s common to see other elements before or after the header, like this:

Header elements have other relationships surrounding it

The markup for this set of elements is:

For the styles, we need to add some s to the left and right of the tags.

Uh oh. `padding` on the large header are doesn’t align with the text

Nooo! 🙁

The on the left and right of is too big!

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

Left and right paddings are now aligned!

Notice the pattern here? The of is twice the size of the of . Yet, the and of are half the and of !

Like in the above case, we can simplify the code if you are open to using a combination of and in your code. Specifically, for left and right s and for top and bottom s:

As you can see, the unit is useful when you need to scale a property with it’s . However, you’ll run into problems if you need to size the property accordingly to the root .

It’s much clearer to see how and can work together in a component now, isn’t it?

Now, let’s take it a notch further and see how the header and paragraph interacts with a grid.

Позиционирование в CSS

Свойства, которые мы раньше использовали для позиционирования, , , , , превратились в новые свойства с префиксом : , , , .

Для английского (LTR):

  • =
  • =
  • =
  • =
/* Старая техника */.popup {  position: fixed;    top: 0;  bottom: 0;  left: 0;  right: 0;}/* Новая техника */.popup {   position: fixed;   inset-block-start: 0;  /* top - для английского */   inset-block-end: 0;    /* bottom - для английского */   inset-inline-start: 0; /* left - для английского */   inset-inline-end: 0;   /* right - для английского */}

Бросив беглый взгляд, вы можете задаться вопросом, какого чёрта я должен использовать такие сложные имена?! Но на то есть веская причина. Новые имена свойств можно комбинировать в шорткаты, подобно текущим , , .

Пример:

.popup {   position: fixed;   inset: 0 0 0 0; /* top, right, bottom, left - для английского */}

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

Псевдокласс соответствия принимает в качестве аргумента простой селектор, составной селектор, список, разделенный запятой, или любую комбинацию этих пунктов. Отлично! Но что же он делает?

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

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

В действительности это уже часть CSS4 (если быть совсем точными, спецификации CSS-селекторов уровня 4), и ещё в этой спецификации сказано, что вы сможете использовать такой же синтаксис — составные селекторы, разделенные запятой — в будущих версиях . Здорово-то как!

На сегодняшний день есть в Chrome и Safari с префиксом , а в Firefox он проходит под своим старым названием, , с префиксом .

rem

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

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

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

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

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

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

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

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

Units

Many CSS properties like , , , etc. take length. CSS has a way to express length in multiple units. Length is a combination of a number and unit with no whitespace. E.g. , etc.

Length

Common Length units

There are several units used by CSS to express length. The older ones, supported by all browsers, are:

  • rem — “r” stands for “root”: “root em” -, which is equal to the font size fixed to the root element (almost always ).
  • vh and vw — Many responsive web design techniques rely heavily on percentage rules. However, CSS percentage measures are not always the best solution for all problems. The measure vh is equal to 1/100 of the height of the viewport. So, for example, if the height of the browser is 800px, 1vh equals 8px and, similarly, if the width of the viewport is 650px, 1vw is equivalent to 6.5px.
  • vmin and vmax — These units are related to the maximum or minimum value of vh and vw. For example, if the browser was set to 1200px wide and the height 600px, 1vmin would be 6px and 1vmax would be 12px. However, if the width was set to 700px and the height set to 1080px, vmin would equal 7px and vmax 10.8px.
  • ex and ch — These units, similar to em and rem, rely on the current font and font size. However, unlike em and rem, these units also rely on as they are determined based on measures specific to each font. The ch unit (“character unit”) is defined as the width of the character zero (“0”). The ex unit is defined as “the current x-height of the current font or the half of 1em”. The height-x of a given font is the height of the lowercase “x” of that font. It is often the middle mark of the font.

There are two general kinds of units used for length and size in CSS: relative and absolute.

Relative Units

Relative units change relative to the element’s current font-size or other settings. Some relative units are

  • the width of a capital letter M of the of the current element.
  • Font sizes are inherited from parent elements.

Example:

Here the will equal since the of the current or parent element is .

  • root , or the width of a capital letter M of the default base .
  • Parent font sizes will have no effect.

Example:

Here the will equal since the default base is .

the percent size relative to a parent’s size.

Example:

Since the parent’s width is , the width of the inner pargraph would be , or 75% of .

view width, or 1/100th of the width of the viewport

Example:

The fill the width of the viewport, whether that is 417px, 690px, or any width.

view height, or 1/100th of the height of the viewport

Example:

This will fill half the height of the viewport, whether that is 1080px, 1300px, or any height.

Absolute Units

Absolute units will be the same regardless of screen size or other settings. Some absolute units are

  • pixel
  • pixel counts are relative to the quality of the viewing device’s screen

, ,

  • inch, centimeter, millimeter
  • An inch is an inch on a small screen or a big screen

,

points (1/72 of an inch) and picas (12 points)

Example

A paragraph with will show up as 24px on a phone, tablet, or desktop screen.

The will show up as 3 inches wide, and the on the will be 3/72 of an inch thick, regardless of the screen size.

Относительно шрифта: em

1em – текущий размер шрифта.

Можно брать любые пропорции от текущего шрифта: 2em , 0.5em и т.п.

Размеры в em – относительные, они определяются по текущему контексту.

Например, давайте сравним px с em на таком примере:

24 пикселей – и в Африке 24 пикселей, поэтому размер шрифта в

А вот аналогичный пример с em вместо px :

Так как значение в em высчитывается относительно текущего шрифта, то вложенная строка в 1.5 раза больше, чем первая.

Выходит, размеры, заданные в em , будут уменьшаться или увеличиваться вместе со шрифтом. С учётом того, что размер шрифта обычно определяется в родителе, и может быть изменён ровно в одном месте, это бывает очень удобно.

Что такое «размер шрифта»? Это вовсе не «размер самой большой буквы в нём», как можно было бы подумать.

Размер шрифта – это некоторая «условная единица», которая встроена в шрифт.

Она обычно чуть больше, чем расстояние от верха самой большой буквы до низа самой маленькой. То есть, предполагается, что в эту высоту помещается любая буква или их сочетание. Но при этом «хвосты» букв, таких как р , g могут заходить за это значение, то есть вылезать снизу. Поэтому обычно высоту строки делают чуть больше, чем размер шрифта.

В спецификации указаны также единицы ex и ch, которые означают размер символа «x» и размер символа «0» .

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

Эти единицы используются чрезвычайно редко, так как «размер шрифта» em обычно вполне подходит.

Font-size Changed in HTML

The first scenario is incredibly common. In fact, almost all web pages use this method set the default property in their CSS:

Here, I chose to use a of 200% in my test, which means that I’m setting both and as . If and are affected by this change in , they should only trigger at

Here’s the result: Chrome, Firefox and IE 11 triggered all three media queries at 400px:

Results from Chrome, Firefox and Internet Explorer 11

This is the correct behavior. and units should not be affected by changes in in the HTML since they’re based on the browser’s internal property.

Unfortunately, we didn’t get the perfect behavior on Safari. It triggered the media query at 800px 🙁

Results from Safari

Since this behavior only occurs on Safari, I was curious to see if mobile Safari was affected as well. Turns out, it did.

So, the first scenario already showed us that we shouldn’t use media queries. However, let’s continue to put rem in the rest of our experiments to see if anything else comes up.

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.

Значения единиц измерения

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

p { font-size: 0.394in; } /* десятичная дробь */
p { margin: -1px; } /* отрицательное значение */

Обратите внимание, что объявление не будет работать, если перед единицей измерения стоит пробел, или если единица измерения не указана (за исключением нулевого значения). Если в качестве значения используется ноль, то указание единицы измерения можно опустить

p { font-size: 1ex; }   /* корректно */
p { font-size: 0; }     /* корректно */
p { font-size: 0ex; }   /* корректно */
p { font-size: 1 ex; }  /* неправильно */
p { font-size: 1; }     /* неправильно */

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

Абсолютные длины

Единицы абсолютной длины являются фиксированными, и длина, выраженная в любом из них, будет отображаться именно как фиксированный размер.

Абсолютные единицы длины не рекомендуются для использования вывода изображения на экране, потому что размеры экранов различных устройств могут сильно отличаться. Однако их можно использовать, если известен выходной носитель, например, для печатного макета (страницы для печати).

Единица Описание
cm сантиметры
Попробуй
mm миллиметры
Попробуй
in дюймы (1 дюйм = 96px = 2.54см)
Попробуй
px * пиксели (1px = 1/96th в 1)
Попробуй
pt точки (1pt = 1/72 в 1)
Попробуй
pc picas (1pc = 12 pt)
Попробуй

* Пиксели (px) относительны и зависят от устройства просмотра. Для устройств с низким разрешением 1 пиксель — это один пиксель (точка) устройства на дисплее. Для принтеров и экранов с высоким разрешением 1px подразумевает несколько пикселей на устройстве.

Относительные единицы измеренияСкопировать ссылку

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

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

Если вы хотите, чтобы этот было меньшего размера шрифта, например, , то что вам делать? Берите калькулятор и считайте, сколько будет 1,2 поделить на 1,4, и в итоге у вас получится:

И проблема не ограничивается использованием . Если вы разрабатываете тянущийся сайт с использованием ширин в процентах, то знаете, что эти проценты соотносятся с размерами контейнера элемента, так что если у вас есть элемент, которому вы хотите поставить ширину в 40% от его родительского элемента, ширина которого — 75%, тогда придется устанавливать ширину этого элемента в 53,33333%.

Мягко говоря, не идеально.

Conclusion

As already mentioned, Simurai deserves the credit for making this technique more widely known. Of course, as he mentions, this is nothing new and the basic concept has been used by many experienced developers for years — but maybe not so much in the context of web components, or modules.

As Simurai says, I think this is a nice method to use when building a CSS framework or library of components, and, if nothing else, I think the technique really drives home the point about how powerful em units are.

If you have any feedback or experience with a similar technique, or have any ideas for how this concept can be improved, I’d be glad to hear your comments.

When to Use Ems

Ems are a relative measure of length. The size of an em is relative to the font-size of its parent element. If you have a <div> with the font size is set to 16px, and a <p> element inside that div with a font-size set to 2em, the font-size of text in the <p> will be 32px; set it to 0.5px, and the font-size will be 8px.

This is useful because it lets you change the absolute size of elements like the font-size without changing their size relative to each other. Lets say you set the font-size of <div> to 22px. Inside that <div> you have a <p> with the width set to 200em, the margins set to 3em, and the font-size set to 0.8em. If you wanted to halve the size of that <p>, you could simply change the font-size on the surrounding <div> to 11px and the width, margins, and font-size on the <p> would scale accordingly.

As you might imagine, this is great for responsive design, where you can set breakpoints for device screen sizes with media queries, change the absolute px measure for elements at different break points, and have all the em-measured elements resize for you — it makes responsive CSS much easier to write and maintain.

What is EM?

This statement doesn’t make sense on the web since we don’t use . It makes complete sense if we substituted with though.

What it means is: if a selector has a of .

The unit can be used to declare font-sizes. In fact, it’s a best practice to use relative units like for .

Consider the following:

What’s the actual size of the selector here?

We have to look at the parent element in order to compute the ‘s . Let’s say the parent element is , and its is set to .

When put this way, we can see that the computed value of is , or .

Although this is possible, it’s often a bad idea to set in the to a pixel value because it overrides the user’s browser settings.

Instead, you can either choose to use a value, or leave out the declaration entirely.

Note: will be set to if you left it out entirely.

For most users (and browsers), a of would default to unless they change the default through their browser settings. It’s rare that anyone would do that though.

Okay so far? Let’s come back to .

can also be used to specify values for other properties in addition to . and are two of such properties that are commonly sized in s.

This is where many people start to get confused with values.

Consider the following code. What should the value be for both the and elements? (Assume of is set to ).

Are you surprised that the computed value of on is different in these two scenarios`?

This phenomenon occurs because is equal to its current . Since the in is now set to . Other properties computed with in would see that .

What throws people off is that can take on different values in different parts of the code. It can be confusing if you’re just starting out with s.

Anyway, that’s . Let’s find out what is next.

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

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

Adblock
detector