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

喜你入骨 提交于 2019-12-24 00:25:10

问题


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

});


来源:https://stackoverflow.com/questions/11070327/center-an-html-element-with-an-unknown-width-to-the-middle-of-the-screen

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!