If I have a HTML element with an unknown width and height, how can I centre it to exactly the middle of the screen?
If it cannot be done with pure CSS, then javascript is OK.
If I have a HTML element with an unknown width and height, how can I centre it to exactly the middle of the screen?
If it cannot be done with pure CSS, then javascript is OK.
This answer may or may not fit your situation, depending on how the unkown width/height are being determined. If the exact dimensions are unkown, but they are set with percentages, then you can use this technique:
#content {
background-color: khaki; /* demo purposes */
position: absolute;
height: 20%;
top: 50%;
margin-top: -10%; /* half the height */
width: 30%;
left: 50%;
margin-left: -15%; /* half the width */
}
See this fiddle for an example. To summarize:
you can do it through jquery..
$(function () {
var element=$("#elementid")
element.css("position","absolute");
element.css("top", Math.max(0, (($(window).height() - this.outerHeight()) / 2) +
$(window).scrollTop()) + "px");
element.css("left", Math.max(0, (($(window).width() - this.outerWidth()) / 2) +
});