Center an HTML element with an unknown width to th

2019-07-23 18:27发布

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.

2条回答
Emotional °昔
2楼-- · 2019-07-23 18:44

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.
查看更多
淡お忘
3楼-- · 2019-07-23 18:44

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

});
查看更多
登录 后发表回答