尝试在屏幕中水平和垂直居中div

时间:2012-01-10 22:25:41

标签: html css center

我正在尝试为我的网站中心的目标网页在屏幕的中心创建一个div,但它无效。

这是我的代码

CSS:

.centerDiv{
width:800px;
margin:0 auto;
border-radius: 5px;
background:#111;
padding:10px;}

HTML:

<div id="centerDiv" class="centerDiv">
   <h1>Title</h1>
   <p>Text will go here.</p>
</div>

感谢。

5 个答案:

答案 0 :(得分:29)

  

注意:如果您尝试水平和垂直居中div,我建议您查看flexbox。你仍然需要提供后备支持,但是flexbox是未来的,它太棒了。

     

更新:现在所有modern browsers都支持flexbox。

首先需要给div一个静态的宽度和高度。

其次,您必须设置position: absolute;left: 50%; top: 50%;,然后您必须执行高度和宽度为HALF的margin-leftmargin-top。然后它会正确显示。

CSS:

.centerDiv{
  width: 800px;
  border-radius: 5px;
  background: #ccc;
  padding: 10px;
  height: 50px;
  position: absolute;
  margin-top: -25px;
  margin-left: -400px;
  top: 50%;
  left: 50%;
}

http://jsfiddle.net/wJ7dY/

P.S。我改变了你的造型,所以你可以真正阅读文字。希望这有帮助!

答案 1 :(得分:15)

此代码(demo)允许设置任何widthheight,而无需更新任何其他属性(例如top = height / 2或依赖于不受支持的技术(例如display:table;。一个缺点是缺乏对旧IE版本的支持。将此与IE的另一个解决方案相结合可能是你最好的选择。

CSS:

.absoluteCenter {
 /* Must manually set width/height */
 width:800px;
 height:500px;

 /* The magic centering code */
 margin:auto;
 position:absolute;
 top:0;bottom:0; /* Aligns Vertically - Remove for Horizontal Only */
 left:0;right:0; /* Aligns Horizontally - Remove for Vertical Only  */

 /* Prevent div from overflowing main window */
 max-width:100%;
 max-height:100%;
 overflow:auto;
}

/* IE 7 and Below */
:first-child+html .absoluteCenter,
* html .absoluteCenter {
 /* Place code here to override all above values, and add IE friendly centering */
}

以及HTML:

<div class="absoluteCenter">
 Content of DIV
</div>

答案 2 :(得分:5)

您要找的是display:tabledisplay:table-cell。无论#center元素的高度如何,此选项都应垂直对齐#parent元素中的#center元素。我相信你需要#parent元素的高度。

<强> HTML

<div id="parent">
<div id="center">
   <h1>Title</h1>
   <p>Text will go here.</p>
</div>
</div>

<强> CSS

#parent{
display: table;
width: /* Your width */;
height: /* Your height */;
}

#center{
position: relative;
display: table-cell;
width: /* Your width */;
height: /* Your height */;
vertical-align: middle;
margin: 0 auto;
}

我昨天在display:table使用body时使用了这个。这项技术应该是compatible through to IE8.

答案 3 :(得分:1)

尝试以下方法:

 .centerDiv{
     position: absolute;
     top: 50%;
     height: 400px;
     margin-top: -200px; /* Half of the height */
     left: 50%;
     width:800px;
     margin-left: -400px; /* Half of the width */
     border-radius: 5px;
     background:#111;
     padding:10px;
 }

答案 4 :(得分:0)

将边距设置为自动而不是0自动,您需要一个高度。我认为100%是为了你的目的。