When to use Em or %?

Asked

Viewed 193 times

2

I’m studying responsive layout and already know that to create a flexible part it is necessary to use relative measure like Em and %. But I still can’t understand what the real difference between one and the other...

...and whether it is possible to achieve the same result using only % and have no problems.

2 answers

3

The units em and ex are relative to the font size. ex is the height of the tiny "x," and em is simply the "font size" (the unit name comes historically from 'the width of the capital "M"', but this definition is not used in CSS).

Exemplo de ex

Thus, if you have an element that needs to be proportional to a body of text (say, a box with text inside, so that the text never leaves the box when the font increases or over space when the font decreases) then the em - or more rarely the ex - is indicated.

Already the % is proportional to the dimensions of the parent element, so if what you want is for example that one element occupies 80% of the available space, and another the remaining 20%, that unit is indicated. There are still the units vw, vh, vmin and vmax which are proportional to the whole screen (regardless of the hierarchy of elements), and which can also be used to specify the font size (cannot define the font-size in %).

1

Here explains the difference between all CSS metrics.

IN

Units of EM values are the most complicated to work with. It is abstract and arbitrary. Here is an example, 1em is equal to the current font size of the element in question, that is, if you have not yet set font size anywhere on the page, then it will automatically pick up the default font size of the browser, which is probably 16px. Then, it is defined that by default 1em = 16px. Say you set the tag body { font-size:20px } then the 1em will become 20px. How it works.

Another example: If you create a tag h1 { font-size: 2em; }, the size of H1 in px will be 32px if you haven’t set some value yet in css.

Percentage %

Percentage as the name says works with value percentage. If a parent has the size of 20px, and you define the child with font-size:50% it will be the size of 10px.

The percentage is very good to work with the tools to grow and decrease the size on the text page.

  • So when is it advantageous to use in? And the to use % in the entire layout and get satisfactory result?

  • 1

    It is not a matter of being advantageous. You should choose the metrica that best suits your layout structure. Yes, you can use % and have a cool result, it depends on who will mount the page.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.