Center an HTML element with an unknown width to th

2019-07-23 18:04发布

问题:

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.

回答1:

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.


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

});