【问题标题】:Is there a way in CSS to get the height (or other property) of an element and share that same value with properties of other elements? [duplicate]CSS中有没有办法获取元素的高度(或其他属性)并与其他元素的属性共享相同的值? [复制]
【发布时间】:2017-10-26 04:50:28
【问题描述】:

例如,我的页面顶部有一个导航栏(就像 Stackoverflow 上的那个)。

因此,body 的 padding-top 应该设置为导航栏的确切高度。

但是,这个导航栏的高度会不时变化,所以我不能依赖像 70px 这样的绝对值来分配 body 的 padding-top 值。

所以,我正在寻找一种纯 CSS 的方法来确保这个 padding-top 始终是相同的值。

我也不能使用 var(),因为我事先不知道导航栏最终的高度。

谢谢。

【问题讨论】:

  • 可能还有其他方法可以完成您想要的布局。你应该发布你的代码。

标签: css frontend


【解决方案1】:

你可以使用 javascript 而不是 css 来做到这一点,但无论如何,正如@Michael B 所说,可能还有其他方法。

使用 javascript 你可以做到:

var nav = document.getElementById("navigationID");
console.log(nav.clientHeight); 
// nav.clientHeight will return integer value of your navigation height.

var nav = document.getElementById("navigationID");
var container = document.getElementById("container");

container.style.paddingTop = nav.clientHeight + "px";
#navigationID
{
  color:#000;
  height:70px;
  width:100%;
  border:4px solid green;
  display:block;
  position:absolute;
}

#container{
  border:1px solid red;
  display:block;
  width:100%;
  height:400px;
  position:relative;
}
<html>
<head>

</head>
<body>
<div id="navigationID"> navigation </div>
<div id="container">
    container
</div>
</body>
</html>

【讨论】:

    猜你喜欢
    • 2017-08-13
    • 1970-01-01
    • 2020-04-22
    • 2013-07-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多