我正在尝试为我的网站中心的目标网页在屏幕的中心创建一个div,但它无法正常工作.
这是我的代码
CSS:
.centerDiv{
width:800px;
margin:0 auto;
border-radius: 5px;
background:#111;
padding:10px;}
Run Code Online (Sandbox Code Playgroud)
HTML:
<div id="centerDiv" class="centerDiv">
<h1>Title</h1>
<p>Text will go here.</p>
</div>
Run Code Online (Sandbox Code Playgroud)
谢谢.
Jas*_*ssi 29
注意:如果您尝试水平和垂直居中div,我建议您查看flexbox.你仍然需要提供后备支持,但是flexbox是未来的,它是惊人的.
更新:现在所有现代浏览器都支持flexbox .
首先需要给div一个静态的宽度和高度.
其次,你必须设置position: absolute;和left: 50%; top: 50%;那么你必须做一个margin-left和margin-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%;
}
Run Code Online (Sandbox Code Playgroud)
PS我改变了你的造型,所以你可以真正阅读文字.希望这可以帮助!
0b1*_*011 15
此代码(演示)允许任何width和height设置,而不必更新任何其他属性(例如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 */
}
Run Code Online (Sandbox Code Playgroud)
和HTML:
<div class="absoluteCenter">
Content of DIV
</div>
Run Code Online (Sandbox Code Playgroud)
你要找的是display:table和display:table-cell.无论#center元素的高度如何,此选项都应垂直对齐#parent元素中的#center元素.我相信你需要#parent元素的高度.
HTML
<div id="parent">
<div id="center">
<h1>Title</h1>
<p>Text will go here.</p>
</div>
</div>
Run Code Online (Sandbox Code Playgroud)
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;
}
Run Code Online (Sandbox Code Playgroud)
我昨天刚用过这个,就用display:table了body.这种技术应该与IE8兼容.
| 归档时间: |
|
| 查看次数: |
70316 次 |
| 最近记录: |