[英]CSS margin-top that changes in function of another element's height
我正在创建一个带有position: fixed;
这样滚动页面时它就不会移动。 但是,我还需要主要内容可见,但使用固定元素,我们看不到主要内容。 基本上,我首先尝试使用具有一定像素数量的边距顶部,但是当我调整窗口大小时,它保持不变。
我所做的是使用 Javascript 使主元素的边距顶部等于标题的高度:
<div class="head" id="head">
</div>
<div class="item main" id="main">
</div>
function margintopchange() {
var main = document.getElementById('main');
var head = document.getElementById('head').getBoundingClientRect();
newhead = head.height.toString();
main.style.marginTop = newhead + "px";
console.log(head.height);
console.log(main.style.marginTop);
}
window.onresize = margintopchange();
window.onresize
也不起作用
这是我的 CSS
.head{
position: fixed;
width: 100%;
border: solid #2196F3 5px;
}
.main {
grid-area: "main";
margin: 0px;
}
问题是每次调整窗口大小时,margin-top 都不会更新,而是每次重新加载页面时都会改变。
我在 Nullish Byte 的评论的帮助下解决了这个问题。 如果有人想知道,如果您这样做,它会起作用:
function marginheader() {
var main = document.getElementById('main');
var head = document.getElementById('head').getBoundingClientRect();
newhead = head.height.toString();
main.style.marginTop = newhead + "px";
}
window.addEventListener('resize', function(event) {
marginheader()
}, true);
marginheader()
//this is so that there is a margin at the beginning
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.