繁体   English   中英

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

[英]Change element padding based on element height and parent height with 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: blockh1样式。 查看这个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>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM