I've been trying to learn responsive coding lately, and the books and tutorials i've gone through have been constantly shifting between using ems and percentages. So i was wondering, when is it appropriate to use ems, and when is it appropriate to use percentages?
Just to clarify other answers, ems do NOT cascade but percentages do. Think of it this way: ems are relative to the current element and percentages are relative to the container. So using a percentage to specify the width of a div inside a div will indeed make the inner one smaller (or larger) than the outer one, but using ems to specify the widths of the same nested divs will specifically make them the width you expect them to be. Generally, you should use ems to specify font typography and percentages to specify element sizes, if you are wanting responsive design.
font-size
property. When you set font-size: 2em
, it will set the font size to 2 times the em length of the parent. I believe this only happens with font-size
though; other properties (like padding: 2em
) will use the em length of the current element. –
Havana This is really a preference. Some will tell you to set body{font-size: 62.5%;}
(which is 10px if the browser's default is 16px) and then use em
s from then on. So, if you want a font-size of 22px you would use 2.2em
. However, most developers have their own opinions on this matter. Some use percentages always. Some use pixels always.
em
is the measurement relative to the current font size, such as:
body{font-size: 16px;}
.someClass{font-size: 1em;} /* 16px */
.someOtherClass{font-size: 2em;} /* 32px */
.anotherClass{font-size: .5em;} /* 8px */
If no font-size
value is set for any parent elements in the document, the browser's default (most likely 16px) font size == 1em
.
Percentages work similarly in that they are relative to the parent container, as opposed to the parent container's font size.
body{width: 800px;}
.someClass{width: 100%;} /* 800px */
.someOtherClass{width: 200%;} /* 1600px */
.anotherClass{width: 50%;} /* 400px */
The issue to look out for in both scenarios is that they both cascade meaning that if you have two classes set with font-size: 2em
and you nest them, you will have 4em
on the inner element.
em and % both are good for responsive web design.
As everybody said em is generally used to define font sizes and % for element like <div>
sizes.
But I found in my experience that using % for elements when you have fonts inside the element can make you element adjust according to the length of font inside it.
For example, if your statement inside the element is completing in 20px 100% is going to give it 20px and if it got completed in 10px, the 100% of div is gonna give it 10px.
So if you are giving some design to a div where you have some fonts/words inside, better use em for preciseness.
© 2022 - 2024 — McMap. All rights reserved.