Hi, I'm Aya Bouchiha, today, I decided to share with you the solution of converting "px" to "rem" or 'em' using a calculator because using It, will distract you to focus more in your work, and will let you waste a considerable amount of time, especially if the project is so big or your computer is slow.
What's px?
- px: is an absolute unit for measuring.
What's them?
- em: is a relative unit to the font-size of its parent, used for measuring, It is equal to 16px.
px vs em vs rem
Converting px to em
by default:
1em = 16px
pxValue = emValue * 16
emValue = pxValue / 16
Should I Use A Calculator For Converting px to em?
- If you are familiar with scss, the answer is no, no, and no! so how?
Creating A Function For Converting px to em
index.scss
@function to-em($val-px){
@return ($val-px / 16) + em;
}
Testing Our Function
index.scss
// index.scss
// px => em
@function to-em($val-px){
@return ($val-px / 16) + em;
}
h1 {
font-size:to-em(24);
}
div {
height: to-em(200);
width: to-em(400);
}
Result
index.css
h1 {
font-size: 1.5em;
}
div {
height: 12.5em;
width: 25em;
}
Have an amazing day!
Top comments (8)
What? No.
1rem
is usually equal to16px
, because that's the common default value for root levelfont-size
, but that's neither the value of1em
, nor in any way a value you should just assume. As soon as you get any nestedfont-size
declarations, this method falls apart very quickly, and unless you apply it extremely consistently (or force a root font size), scaling gets thrown off a bit by this.Don't calculate
em
based onpx
values! Familiarize yourself with howfont-size
works, and consider specifically what you want to achieve: Do you want your type to scale with the user's (or container's)font-size
, or do you simply want to avoid usingpx
values "because that's best practice"?Thank you for the feedback 🙏🏻
Short and to the point!
Just one suggestion..
Instead of kebab-case, it would be good if you use camelCase as I happen to read the function as 'value - px divided by 16' 😣
There might be more like me or I may also happen that I've just woke up from sleep 😁.
Once again, keep bringing new articles. 🤩
Thank you a lot for your feedback, have an amazing day!
👍
😊
I actually didn't even know about 'em' or 'rem' , so I read your linked article 'Sizing in Css: px vs em vs rem'. Keep up the good work!
I appreciate that a lot!