使用javascript根据元素高度和父级高度更改元素填充



我需要根据h1及其父对象的高度更改h1顶部填充的大小。衬垫顶部为(h1的高度-h1的父高度(/2

我仍然不明白为什么JavaScript代码不起作用。

window.onload = function() {
const h1 = document.getElementsByTagName("h1")[0];
h1.innerHTML = document.title;
h1.style.paddingTop = (((h1.parentElement.clientHeight - h1.clientHeight) / 2).toString());
console.log(((h1.parentElement.clientHeight - h1.clientHeight) / 2).toString());
}
header {
border-bottom: solid 1px black;
position: fixed;
height: 10vh;
width: 100%;
}
h1 {
margin: 0px;
margin-top: auto;
}
<header>
<h1>Text</h1>
</header>

这仅仅是因为您没有使用单元来识别评估填充的值。另外,将display: block添加到h1样式中。看看这个JSBin演示。

window.onload = function() {
const h1 = document.getElementsByTagName("h1")[0];
h1.innerHTML = document.title;
h1.style.paddingTop = (((h1.parentElement.clientHeight - h1.clientHeight) / 2).toString())+'vh'; // Use unit.
console.log(((h1.parentElement.clientHeight - h1.clientHeight) / 2).toString());
}
header {
border-bottom: solid 1px black;
position: fixed;
height: 10vh;
width: 100%;
}
h1 {
margin: 0px;
margin-top: auto;
display: block;
}
<header>
<h1>Text</h1>
</header>

最新更新