Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

CSS Unused CSS Stages Media Queries Adaptive Layouts with Media Queries

Paul Murphy
Paul Murphy
6,162 Points

Pixel to Percentage conversion

Could some kind person remind me how to convert pixels to percentages for a fluid layout?

Forgive me I've been away for a while and now I'm brushing up my skills!

4 Answers

Chris Dziewa
Chris Dziewa
17,781 Points

Just remember target / context. The context for regular width and for margin is based on the containing element. The context for padding is the element itself.

Ex: Finding the width in percentage of a 200px div inside a 1000px container:

200 / 1000 = .2 => Move decimal place over two to the right and this leaves you with 20% width.

Ex2: Convert left and right padding of a div to percentage where padding is 10px and element width is 350px and everything is inside a 1000px container. Here we disregard the overall container since we are dealing with padding leaving us with context being 350px and the target of 10px. Our left and right padding would then be:

10 / 350 = 0.02857142857142857 (Keep entire decimal to make sure everything is mathematically perfect) => Move decimal point over two to the right leaving you with 2.857142857142857% left and right padding.

Target/context then move the decimal two places to the right. \

Example: let's say a div is 640px and you need 20px in padding converted to %.

20px/640px = 0.03125 = 3.125%

edit: Chris got to it before me.

Paul Murphy
Paul Murphy
6,162 Points

Thanks for the reply!

Hi guys,

I would like to ask a question here too. I understood this method of target/context. But how I can convert a pixel value to a percentage value? When I need to implement a Firework layout every element have pixel dimensions (for example a element with 150x100 px). Do you guys know how can I convert those dimensions to percentage and make it work in a fluid layout?

Many thanks!

For example, if you are using 20px as your font size then the percentage would be 125%. 20 / 16 = 1.25. You would always calculate any pixels size with 16. You would move your decimal point to the right 2 times no matter what to get your answer.