如何获取具有继承宽度的元素的宽度

How to get the width of an element which has inherit-width?

本文关键字:继承 元素 何获取 获取      更新时间:2023-09-26

我有一个响应式网站。此外,我还有一些嵌套元素,它们使用了百分比(%)宽度。现在我想得到一个子元素的宽度,并将其设置为另一个元素的宽度。

注意:我可以获得我需要的元素的宽度,并使用JavaScript将其设置为另一个元素(类似于$('.children')[0].getBBox().width;)。但我想知道,我有可能使用纯CSS来做到这一点吗?

这是我的HTML结构和CSS代码:

#grandfather {
  width: 70%;
  border: 1px solid #666;
  padding: 5px;
}
.father {
  width: 80%;
  border: 1px solid #999;
  padding: 5px;
}
.children {
  width 90%;
  border: 1px solid #ccc;
  padding: 5px;
}
.follow-width {
  position: absolute;
  border: 1px solid #ccc;
  padding: 5px;
  /* width: ? */
}
<div id="grandfather">
  <div class="father">
    <div class="children">how to get the width of this element?</div>
  </div>
</div>
<br>
<hr>
<br>
<div class="follow-width">
  this element needs to the width of div.children
</div>

不,您不能只在CSS中执行此操作。

但是你在InternetExplorer之前的版本8是可能的:

width: expression(document.getElementById("grandfather").style.width);

#grandfather {
  width: 70%;
  border: 1px solid #666;
  padding: 5px;
}
.father {
  width: 80%;
  border: 1px solid #999;
  padding: 5px;
}
.children {
  width 90%;
  border: 1px solid #ccc;
  padding: 5px;
}
.follow-width {
  position: absolute;
  border: 1px solid #ccc;
  padding: 5px;
  width: expression(document.getElementById("grandfather").style.width);
}
<div id="grandfather">
  <div class="father">
    <div class="children">how to get the width of this element?</div>
  </div>
</div>
<br>
<hr>
<br>
<div class="follow-width">
  this element needs to the width of div.children
</div>