国内最全IT社区平台 联系我们 | 收藏本站
华晨云阿里云优惠2
您当前位置:首页 > web前端 > htmlcss > Div 内容垂直居中

Div 内容垂直居中

来源:程序员人生   发布时间:2015-05-19 08:26:05 阅读次数:3635次


感觉 CSS 有很多可以hack 的,好玩的地方。

想了1个简单的,诡异的办法,让Div 中想展现的内容垂直居中。

而不去使用 flexbox, JS, Less, Scss, rotate, before, after。

可以在 container 头部塞1个与“内容区域”1样大小的 div,然后设置“内容区域”的 bottom 为父亲的 50%,

最后计算下,会发现“内容区域”上下距离相等。


<html> <head> <style type="text/css"> #container { position: relative; left: 200px; top: 100px; width: 100px; height: 400px; background-color: #7873fa; } #offset-head { height: 50px; } #offset-body { width: 100px; height: 350px; position: relative; } #show { width: 100px; height: 50px; background-color: #ffbc3e; position: absolute; bottom: 50%; } </style> </head> <body> <div id="container"> <div id="offset-head"></div> <div id="offset-body"> <div id="show"></div> </div> </div> </body> </html>


效果图:


不过代码产生改动的时候,比如:

将黄色 (show ) 变高时,需调剂offset-headheight使showoffset-head 二者的height1样高。

改动 containerheight 时,需将offset-bodyheight 改成container.height - offset-head.height


生活不易,码农辛苦
如果您觉得本网站对您的学习有所帮助,可以手机扫描二维码进行捐赠
程序员人生
------分隔线----------------------------
分享到:
------分隔线----------------------------
关闭
程序员人生