Joh*_*hnW 7 html css html-table center centering
假设我想在视口的中心放置一个元素,用作弹出消息.它应该满足以下要求:
如果没有采用下面的基于表格的解决方案,有没有更好的方法来实现这一目标?
<table style="position:absolute;width:100%;height:100%">
<tr>
<td align="center">
<span id="centeredContent">I always remain centered</span>
</td>
</tr>
</table>
Run Code Online (Sandbox Code Playgroud)
最好的解决方案(在我看来)是使用绝对定位将元素的左上角放置在50%/ 50%,然后使用负边距将元素推回到中心.唯一的缺点是您必须指定元素的宽度和高度.这是一个例子:
HTML:
?<div id="centerme">
Hello, world!
</div>?
Run Code Online (Sandbox Code Playgroud)
CSS:
?#centerme
{
position: absolute;
left: 50%;
top: 50%;
/* You must set a size manually */
width: 100px;
height: 50px;
/* Set negative margins equal to half the size */
margin-left?: -50px;
margin-top: -25px;
background-color: cornflowerblue;
}
Run Code Online (Sandbox Code Playgroud)
这是jsfiddle的演示:http://jsfiddle.net/UGm2V/
如果您确实需要居中的内容具有动态高度,那么就有了更高级的解决方案.要知道它在旧的IE浏览器中不起作用.HTML如下:
<div id="outter-container">
<div id="inner-container">
<div id="centred">
<p>I have a dynamic height!</p>
<p>Sup!</p>
</div>
</div>
</div>
Run Code Online (Sandbox Code Playgroud)
外部容器需要覆盖页面的宽度和高度.它是具有绝对定位的块元素.
内部容器实际上是一张桌子!这是由display: tablecss属性决定的.这里的胜利是你实际上不需要任何表HTML.
#centred div是最后一个必需元素.它仍覆盖页面宽度和高度的100%,但放在其中的任何内容都将在垂直和水平方向上居中.这是你需要的css,并附有解释:
/*
An outter container is needed because the table
won't cover the page width and height on it's own
*/
#outter-container
{
position: absolute;
top: 0px;
right: 0px;
bottom: 0px;
left: 0px;
}
/*
The inner container is a table which is set to
cover the width and height of the page.
*/
#inner-container
{
display: table;
width: 100%;
height: 100%;
}
/*
This table cell will cover 100% of the page width
and height, but everything placed inside it will
be placed in the absolute centre.
*/
#centred
{
display: table-cell;
vertical-align: middle;
text-align: center;
}
Run Code Online (Sandbox Code Playgroud)
当然,这是一个jsfiddle演示:http://jsfiddle.net/N7ZAr/3/
| 归档时间: |
|
| 查看次数: |
6152 次 |
| 最近记录: |