创建一个垂直和水平居中的html div [英] Creating a vertically and horizontally centered html div
问题描述
我想要建立类似Google首页的网页。它是一个位于中心的输入框和在页面顶部显示链接的div。如果我改变浏览器窗口的大小,我也希望页面动态调整大小。我已经实现部分成功使用yui2网格css和一个表。以下是一段代码:
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>
此html的唯一问题是页面
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 ?
推荐答案
您可以使用jQuery来设置浏览器窗口的大小它完美。
You can use jQuery to set it to perfectly.
$(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();
$ b b
CSS
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' */
}
这篇关于创建一个垂直和水平居中的html div的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!