开发者

Creating a vertically and horizontally centered html div

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; heigh开发者_如何转开发t: 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 ?


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' */
}​
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜