I want to position an HTML element in the horizontal middle and vertical golden ratio with CSS only. The height of the element must be absolutly flexible, so I can not just set the top-attribute
and the element-height
to a percentage value. Is there any way to do that?
Schematic representation:
In the image, arrows of the same color are in golden ratio to each other (38.2% : 61.8%). The dotted line is only imaginary.
I believe the math works out to be this (vertical centering only discussed here):
See Fiddle (thanks to Daniel for making that)
CSS
That should get your ratio correct for green. Height is flexible to viewport size.
EDIT: More explanation. Note that the blue arrows start out dividing 100% of the height into 38.2 and 61.8. The red top arrow is going to be 61.8 of the top blue section (38.2), hence 23.6. The red bottom arrow is going to be 61.8 of the bottom blue section (61.8), hence 38.2. Now the double check: 23.6 + 38.2 = 61.8 (that is the TOTAL distance of the two red arrows added together). So their ratio is 23.6/61.8 = 38.2% and 38.2/61.8 = 61.8% (red arrows meet your golden ratio). The green is 100 - 61.8 (the red arrow totals) = 38.2 (the total green area). The top green arrow is 38.2 (top blue) - 23.6 (top red) = 14.6. The bottom green area is 61.8 (bottom blue) - 38.2 (bottom red) = 23.6 (bottom green). Let's check the green ration: 14.6/38.2 = 38.2% and 23.6/38.2 = 61.8% (green arrows meet your golden ratio). Here's a golden ratio addict html/css version of your picture (I know your picture was for illustration purposes, but this was fun):
HTML
CSS
EDIT 11-10-11: Based on the questioner's comment that my first interpretation above was not correct. I offer the fact that my solution will still work assuming the white area is the content container controlling the height (in case this is useful for anyone). In such a case, do this:
HTML
CSS--first, remove
html
andbody
CSS from above. Then add:Finally I found an answer, after eight years :D
Because of new CSS technologies :)
see my CodePen: https://codepen.io/eHtmlu/pen/ExjZrQb
or the same live example here on stackoverflow:
Okay, I've tested this and it appears to work. The trick though requires the two
div
s,inner
anddummy
to have exactly the same contents.dummy
is used to give theouter
div the appropriate height so that theinner
div can be positioned by a percentage of that height. A bit hacky but no javascript.http://jsfiddle.net/fVQeC/4/