Responsive CSS absolute top position

MichaelDeBoey picture MichaelDeBoey · Jan 18, 2016 · Viewed 8.2k times · Source

I need your help! Been searching for a solution, but couldn't find one, so thought I should just ask it.

For a school project I need to postion a random number of halls into the right position on a map. As an example I just used 4 halls an just hard coded all the info that's retreived from a JSON with Angular as you can see in this CodePen

<div class="hall" id="hall01" style="width:15%; padding-bottom:50%; left:00%; top:00%; background-color:red;"></div>
<div class="hall" id="hall02" style="width:85%; padding-bottom:20%; left:15%; top:00%; background-color:green;"></div>
<div class="hall" id="hall03" style="width:15%; padding-bottom:10%; left:85%; top:40%; background-color:yellow;"></div>
<div class="hall" id="hall04" style="width:85%; padding-bottom:20%; left:15%; top:60%; background-color:blue;"></div>

I already have solved the issue of resizing the halls, when the page gets resized. The only problem that remains is that the absolute positioning with top isn't working like it should.

Everything is calculated with a width of 1000px and a height of 500px in mind, but it should all resize if the browser also resizes.

Also getting the parent to adjust to the right height is something I struggle with. Can somebody please help me with this?

Answer

yts picture yts · Jan 19, 2016

The problem is that when using the top property, percentages are calculated based on the height of the container, not its width. To fix this, set the top to 0 and then use margin-top: x%;. All margins are calculated based on the container's width, so the margin-top will shrink as well when the window is resized.