html元素在网页中垂直居中,在视口中垂直和水平居中HTML元素的最佳方法是什么?...

最好的解决方案(在我看来)是使用绝对定位将元素的左上角放置在50%/ 50%,然后使用负边距将元素推回到中心.唯一的缺点是您必须指定元素的宽度和高度.这是一个例子:

HTML:

Hello,world!

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;

}

如果您确实需要居中内容具有动态高度,那么就有了更高级的解决方案.要知道它在旧的IE浏览器中不起作用. HTML如下:

I have a dynamic height!

Sup!

外部容器需要覆盖页面的宽度和高度.它是具有绝对定位的块元素.

内部容器实际上是一张桌子!这是由display:table css属性决定的.这里的胜利是你实际上不需要任何表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;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值