When to use CSS instead of percent in CSS?

Recently, I have been trying to learn responsive coding, and the books and training materials that I have experienced are constantly changing between using ems and percentages. Therefore, I was wondering when it is advisable to use ems, and when it is advisable to use interest?

+4
source share
3 answers

To clarify the other answers, ems are NOT cascaded, but percent. Think of it this way: ems refer to the current item, and percentages refer to the container. Thus, using percent to indicate the width of the div inside the div will cause the inner unit to be smaller (or larger) than the outer, but using ems to indicate the width of the same nested divs will specifically make them the width you expect them to be . Typically, you should use ems to indicate font typography and percentages to indicate element sizes if you need a responsive design.

+4
source

This is really a preference. Some will tell you to set body{font-size: 62.5%;} (this is 10px if the default browser is 16px) and then use em from now on. So, if you want a 22px font size, you would use 2.2em . However, most developers have their own opinions on this issue. Some always use interest. Some use pixels always.

em is a measurement relative to the current font size, for example:

 body{font-size: 16px;} .someClass{font-size: 1em;} /* 16px */ .someOtherClass{font-size: 2em;} /* 32px */ .anotherClass{font-size: .5em;} /* 8px */ 

If no font-size set for any parent in the document, the default browser font size (most likely 16 pixels) == 1em .

The percentage works similarly to the fact that they relate to the parent container, in contrast to the font size of the parent container.

 body{width: 800px;} .someClass{width: 100%;} /* 800px */ .someOtherClass{width: 200%;} /* 1600px */ .anotherClass{width: 50%;} /* 400px */ 

The problem in both scenarios is that both cascades mean that if you have two classes with font-size: 2em and you font-size: 2em them, there will be 4em in the inner element.

+1
source

em and% are both good for responsive web design.
As everyone said, em is usually used to determine font sizes and% for an element of type <div> .
But I have found in my experience that using% for elements, when you have fonts inside an element, can make you adjust the element according to the length of the font inside it.
For example, if your statement inside an element ends in 20px 100%, it will give it 20px, and if it completes in 10px, a 100% div will give it 10px.
Therefore, if you are giving some kind of div design in which you have some fonts / words inside, it is better to use em to ensure accuracy.

0
source

Source: https://habr.com/ru/post/1485095/


All Articles