Div 內容垂直居中
來源:程序員人生 發布時間:2015-05-19 08:26:05 閱讀次數:4033次
感覺
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-head 的height,使show
與offset-head 二者的height1樣高。
改動
container 的height
時,需將offset-body
的height 改成container.height
- offset-head.height
生活不易,碼農辛苦
如果您覺得本網站對您的學習有所幫助,可以手機掃描二維碼進行捐贈