![](/img/trans.png)
[英]How do you make an HTML element hear a document.body scroll on vue 3?
[英]How do you vertically align the body tag of an HTML document?
我有一個水平居中但相對較短的網頁-它只占垂直頁面的一半。 我希望它居中。 如何將標簽垂直居中? 我不能有一個固定的身高,所以這不是一個選擇。 如果CSS不夠強大,我可以使用Javascript完成此工作嗎? 謝謝!
兩種主要方法,都不是特別完美,但被廣泛使用:
1)如果您的內容確實是一個已知的固定高度,則可以使用
position: absolute;
top: 50%;
margin-top: here, set a pixel value that's equal to: -1 * (content height / 2)
2)如果您不在乎它在IE7及更低版本中的工作方式是否相同,請按如下所示設置CSS:
html { display: table; }
body { display: table-cell; vertical-align: middle; }
如果您不介意添加非語義標記,則可以執行以下操作:
HTML:
<div class="pusher"></div>
<div class="center"></div>
CSS:
html, body {
height: 100%;
}
.pusher {
height: 100%;
margin-bottom: -50%;
}
.center {
background: green;
width: 400px;
height: 200px;
margin: 0 auto;
}
如果您確實關心語義標記,並且必須支持較舊的瀏覽器,那么您將不得不使用JavaScript。 這是使用jQuery的一種解決方案:
var $window = $(window),
$container = $('#container');
$window.resize(function(){
$container.css('margin-top',
Math.max(($window.height() / 2) - ($container.height() / 2), 0)
);
}).resize();
這是小提琴: http : //jsfiddle.net/dw3rc/
我經常通過設置height:50%和padding-top:25%來做到這一點,但這並不總是合適的。
此頁面標識了可能有效的另一種技術:
http://www.jakpsatweb.cz/css/css-vertical-center-solution.html
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.