I’m trying to make an iPad-like popover div as an exercise, but I can’t find out how to vertically center the popover div, having an unspecified content width/height.
I want the triangle to point to the position defined by #popover-wrapper’s top/bottom right/left values, but top: -50% does not work.
Thanks for your help 🙂
If you do not want to use javascript, then centering it vertically is not possible (as previously stated by others). However, if your goal is to simply have a nice pop-up that allows some flexible width/height, I recommend the following pure CSS solution. Some explanation follows each section for what I did and why I did it.
OPTION #1 HTML (my preferred)
The triangle
divis gone, because I am going to use an:afterpseudo class to apply it since it is purely presentational.OPTION #1 CSS (note the
#triangle-tipcode was replaced with#popover-direction-setter:after)Do not be alarmed by the
#popover-direction-setterhavingwidthset. I presume you know theleftposition (since you use it), so thiswidthcan be pre-calculated and makes a maximum width that the pop up will be so that it does not end up flowing off the left side of the browser window. I would think that would be a good thing.The
min-heightis set on#actual-popover-divso that if content is minimal, it looks good with the triangle.The
topposition of#actual-popover-divis offsetting youremsizing on thepadding. Themargin-topon that element is just bumping up enough to make the arrow sit nicely in the upper corner, and be centered when themin-heighttakes effect.OPTION #2 HTML (keeps triangle
divbut repositions it)OPTION #2 CSS remains as you originally had the triangle
divand eliminates my:afterpseudoclass code.I know this does not meet your challenge requirements fully. Again, I agree with others that there is no way currently to position an element centered vertically with an undetermined height. However, if nothing else, others may find my solution good for them.