Навіщо використовується розмір emНавіщо використовується розмір em

0 Comment

Просте перетворення PX у EM(REM)

Пікселі та point є статичними вимірюваннями. 1 піксель завжди 1 піксель. 1 point завжди 1 point. Points дещо відрізняються, оскільки вони змінюють розмір залежно від DPI. На папері з вищою роздільною здатністю 12-точковий текст фактично містить більше пікселів, ніж 12-точковий текст на моніторі комп’ютера, який має нижчу роздільну здатність, ніж папір. Відсоток і EM, з іншого боку, є відносними вимірюваннями. Розмір EM або відсоткового тексту залежить від його батьківського елемента. Якщо основний текст має розмір 12 пікселів, тоді текст, встановлений на 120% або 1,2 EM всередині основної частини, матиме 1,2 * 12 або 14,4 пікселів.

НАВІЩО РОЗМІРЮВАТИ РОЗМІР ТЕКСТУ ЗА ДОПОМОГОЮ EMS У CSS?

Таблиці стилів, які використовують EM, легше підтримувати для дизайнера та доступніші для кінцевих користувачів. Таблиці стилів стало легше підтримувати, оскільки весь текст, набір в EM, масштабується відповідно до основного розміру шрифту. Потрібно змінити лише розмір шрифту одного елемента, а не окремо змінювати розмір шрифту кожного елемента. Доступність покращена для кінцевих користувачів, оскільки текст масштабується на основі їхніх уподобань, а не встановлюється статично в пікселях. Крім того, кінцеві користувачі можуть використовувати гарячі клавіші для масштабування тексту в усіх браузерах. Багатьом людям важко читати дрібний текст на екрані комп’ютера.

Why em instead of px?

I heard you should define sizes and distances in your stylesheet with em instead of in pixels. So the question is why should I use em instead of px when defining styles in CSS? Is there a good example that illustrates this?

For what it’s worth, here’s the definition for the different units in CSS: w3.org/TR/css3-values/#lengths.

15 Answers 15

It is wrong to say that one is a better choice than the other (or both wouldn’t have been given their own purpose in the spec). It may even be worth noting that Stack Overflow makes extensive use of px units. It is not the poor choice that the question suggests it is.

Definition of units

  • px is an absolute unit of measurement (like in, pt, or cm) that also happens to be 1/96 of an in unit (more on why later). Because it is an absolute measurement, it may be used any time you want to define something to be a particular size, rather than being proportional to something else like the size of the browser window or the font size. Like all the other absolute units, px units don’t scale according to the width of the browser window. Thus, if your entire page design uses absolute units such as px rather than %, it won’t adapt to the width of the browser. This is not inherently good or bad, just a choice that the designer needs to make between adhering to an exact size and being inflexible versus stretching but in the process not adhering to an exact size. It would be typical for a site to have a mix of fixed-size and flexible-sized objects. Fixed size elements often need to be incorporated into the page – such as advertising banners, logos or icons. This ensures you almost always need at least some px-based measurements in a design. Images, for example, will (by default) be scaled such that each pixel is 1px in size, so if you are designing around an image you’ll need px units. It is also very useful for precise font sizing, and for border widths, where due to rounding it makes the most sense to use px units for the majority of screens. All absolute measurements are rigidly related to each other; that is, 1in is always96px, just as 1in is always72pt. (Note that 1in is almost never actually a physical inch when talking about screen-based media). All absolute measurements assume a nominal screen resolution of 96ppi and a nominal viewing distance of a desktop monitor, and on such a screen one px will be equal to one physical pixel on the screen and one in will be equal to 96 physical pixels. On screens that differ significantly in either pixel density or viewing distance, or if the user has zoomed the page using the browser’s zoom function, px will no longer necessarily relate to physical pixels.
  • em is not an absolute unit – it is a unit that is relative to the currently chosen font size. Unless you have overridden the font style by setting your font size with an absolute unit (such as px or pt), this will be affected by the choice of fonts in the user’s browser or OS if they have made one, so it does not make sense to use em as a general unit of length except where you specifically want it to scale as the font size scales. Use em when you specifically want the size of something to depend on the current font size.
  • rem is like em, but it’s relative to the base font size of the document (specifically, of the root element), rather than the font size given to the current element.
  • % is also a relative unit, in this case, relative to either the height or width of a parent element. They are a good alternative to px units for things like the total width of a design if your design does not rely on specific pixel sizes to set its size. Using % units in your design allows your design to adapt to the width of the screen/device, whereas using an absolute unit such as px does not.
  • vh, vw, vmin, and vmax are relative units like %, but they are relative to the size of the viewport (size of the viewable area of the window) rather than of the parent element. Respectively, they are relative to the viewport’s height, width, smaller of the two, and greater of the two.

EMs до Centimeters

CSS має набір різних одиниць, які можна використовувати для позначення розміру шрифтів та інших елементів, таких як ширина, поля, відступи тощо. Вибір та оцінка зв’язків між одиницями CSS може бути складним для обчислення, тому наш онлайн-конвертер EMs в Centimeters допоможе вам перемикатися між ними в найкоротші терміни.

За допомогою конвертера EMs в Centimeters ви також можете виконати зворотне обчислення від centimeters до ems. Наш застосунок працює на всіх платформах, включаючи Windows, Linux, Mac OS, Android та iOS. Не потрібна реєстрація, плагін або установка програмного забезпечення.

  • Швидкий спосіб перетворення EMs в Centimeters і навпаки
  • Без обмежень, без реєстрації та встановлення додаткового програмного забезпечення
  • Спробуйте інші перетворення пікселів: px в мм, px в см, px в дюйм,px в pt, px в rem, px в em
  • Зручний інтерфейс та прості налаштування для перетворення EMs в Centimeters
  • Працюйте з вашого улюбленого пристрою

Як конвертувати EMs в Centimeters

  • Спочатку виберіть пару одиниць для перетворення, наприклад, ems у centimeters.
  • Введіть базове значення, якщо воно потрібно.
  • Натисніть кнопку «Конвертувати», щоб запустити перетворення ems в centimeters і негайно отримати результат у текстовому полі.
  • Ви можете вибрати нову пару одиниць CSS для перетворення або запустити зворотне перетворення одиниць.

FAQ

  • Навіщо потрібен конвертер EMs в Centimeters? Якщо вам потрібно розрахувати розміри, пов’язані з ems для різних випадків, скористайтеся нашим конвертером EMs в Centimeters. Він миттєво перетворює pixels, points, root units, дюйми, сантиметри та інші одиниці розміру CSS!
  • Що таке піксель у CSS? Піксель (px) – це одиниця виміру, яка зазвичай використовується в графічному та веб-дизайні. Термін CSS піксель є синонімом одиниці CSS абсолютної довжини px – яка нормативно визначається як рівно 1/96-та від 1 дюйма.
  • Що таке точка (point) в CSS? Point (pt) – це одиниця довжини, яка зазвичай використовується в друкованій промисловості та друкованих засобах масової інформації для досягнення ідеального відображення пристрою. Одна точка еквівалентна 4/3 фізичних пікселів. Point дорівнює 1/72 дюйма. Наприклад, 12 pt = 16 пікселів.
  • Що таке em в CSS? У CSS один em визначається як поточний розмір шрифту. Em – відносна одиниця CSS. Для більшості елементів це успадковане та обчислюване значення від його батьківського (базового) елемента. Кореневий елемент особливий тим, що не успадковує нічого. 1 em для кореневого елемента – це розмір шрифту за замовчуванням, вказаний в налаштуваннях браузера – 16 px в більшості сучасних браузерів Windows. Вираження розмірів, таких як поля та відступи, в em означає, що вони пов’язані з розміром шрифту, а розміри будуть пропорційними.