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

Ziya Jamalov
Ziya Jamalov
6,116 Points

PX to % - Build a Responsive Website

Hi. I'd like to know, how to convert px to percent in margin top and bottom of images, if they parents-widths undefined? Example from code of video-lesson in project "Build a Responsive Website" was - margin:0 0 20px 0 become - margin:0 0 5% 0 By formula target รท context = result, context is 400px. But I can't find, where this number was taken?

2 Answers

Tom Bedford
Tom Bedford
15,645 Points

From w3: Both padding and margin all percentages reference the "width of the containing block".

I made a codepen where you can play around with it. I have an image inside a div with margins set as %s. You can see how the image is positioned in relation to the div width rather than height.

Maximiliane Quel
PLUS
Maximiliane Quel
Courses Plus Student 55,489 Points

I'm not quite sure which image you are referring to specifically, but as all the images on the Smell's like baking website are part of a containing div with a grid and potentially omega class applied and the images are set to have a max-width of 100%.

<div id="new-cupcakes" class="grid_5 omega">
.grid_5 { width: 40.5%; } /* 405px/1000px = 0.405px */
.omega{margin-right:0;}

20px/385px=0.05194805

which would approximately give you your margin. I think from this post you can see that they might have rounded the numbers to the nearest ten: post. I know that they advise against rounding but there you are.

Ziya Jamalov
Ziya Jamalov
6,116 Points

<p>Thanks :) At first i thought so... but then studied code in Chrome DevTools.</p> <p>Margin bottom 5% is out of line 20px. 5% of img in grid 7 is equal to 28.750px and context then is 575px (width of grid 7). </p> <p>Then... So, we can set our own margins percentage for bottom and the top, and it's not important what pixel-value was set there before?</p>

Maximiliane Quel
Maximiliane Quel
Courses Plus Student 55,489 Points

I'm sorry? Is your question why original value doesn't quite match 20px?

I can't answer that. I can only imagine someone thought 0.03478261 was reasonably close to 5% so it wouldn't make a difference ... but I'm pretty sure the logic above applies.