简体   繁体   English

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

[英]Change element padding based on element height and parent height with javascript

I need to change the size of h1's top padding based on the height of h1 and it's parent.我需要根据 h1 的高度和它的父级来更改 h1 的顶部填充的大小。 Padding top would be (h1's height - h1's parent height) / 2填充顶部将是(h1 的高度 - h1 的父高度)/ 2

I still don't understand why the JavaScript code isn't working.我仍然不明白为什么 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>

Simply because you have not used a unit to identify the value of evaluated padding.仅仅是因为您没有使用单位来识别评估填充的值。 Additionally add display: block to the h1 style.另外添加display: blockh1样式。 Checkout this JSBin demo.查看这个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