Creating a vertically and horizontally centered html div

假装没事ソ 提交于 2019-12-06 13:43:08

问题


I am trying to create a page similar to Google's homepage. It is to have a centrally located input box and a div on top of the page displaying links. I also want the page to resize itself dynamically if I change the size of the browser window. I have achieved partial success using yui2 grid css and a table. Here's a snippet:

<body>
  <div id="doc3">
    <div id="hd"><a style="float:left" href="link1.com"> link1</div> 
    <div id="bd" style="display: table; height: 400px;">
      <div style="display: display: table-cell; vertical-align: middle">
        <input name="searchbox" value="searchinput" size="40" />
        <input name="submit" type="submit" value="search />
      </div>
    </div> 
  </div>
</body>

The only issue with this html is that the page doesn't dynamically resize upon resizing the browser window. Is there a better way of doing this ?


回答1:


You can use jQuery to set it to perfectly.

jQuery

$(window).resize(function() {
    var wh = (($(window).height()-$('#center').height())/2)+'px';
    var ww = (($(window).width()-$('#center').width())/2)+'px';
    $('#center').css({
        top: wh,
        left: ww
    });
}).resize();

CSS

#center {
    border: 1px solid black;
    position: absolute;
    width: 50px;
}​

If you don't care about perfectly vertically centered, you could do:

#center {
    border: 1px solid black;
    margin: 0 auto;
    position: relative;
    width: 50px;
    top: 45%; /* or whatever % looks 'right' */
}​


来源:https://stackoverflow.com/questions/3703178/creating-a-vertically-and-horizontally-centered-html-div

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