starbeamrainbowlabs
starbeamrainbowlabs

Reputation: 6106

Center an HTML element with an unknown width to the middle of the screen

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.

Upvotes: 2

Views: 340

Answers (2)

Jeroen
Jeroen

Reputation: 63699

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.

Upvotes: 2

Rab
Rab

Reputation: 35572

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

});

Upvotes: 2

Related Questions