2

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.

starbeamrainbowlabs
  • 5,692
  • 8
  • 42
  • 73
  • Easy to implement CSS only solution: http://stackoverflow.com/questions/10939288/how-can-i-vertically-center-text-in-a-dynamically-high-div/10939940#10940314 – doptrois Jun 17 '12 at 10:43

2 Answers2

2

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) + 

});
Raab
  • 34,778
  • 4
  • 50
  • 65
  • 1
    You probably can, but that would mean dealing a lot more with browser differences yourself... – Jeroen Jun 17 '12 at 09:55
2

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:

  • Con: only applicable if the exact dimensions are unkown because they are specified in %.
  • Pro: pure CSS solution.
Jeroen
  • 60,696
  • 40
  • 206
  • 339
  • but the OP said: "Center an HTML element **with an unknown width** to the middle of the screen" – epeleg Jun 17 '12 at 10:12
  • I know, but it's not specified if only the **exact width** or *both the **exact and relative width*** are unkown. If someone stumbles on this question because he has a `%` width (and thus an **unkown exact width**) my answer may be of use. – Jeroen Jun 17 '12 at 10:23
  • I see your point but having struggled with similar issues I doubt that when he says that the width is unknown he means that it has a known width in %. Had that been the case he would have probably asked about vertical centering... still maybe it will help someone in the future. – epeleg Jun 17 '12 at 10:37
  • thank you! This solution is way simpler than the one above. Marked as the answer. – starbeamrainbowlabs Jun 17 '12 at 11:41