百分比宽度,指父级的父级

时间:2017-01-25 19:06:49

标签: html css parent-child percentage

我想弄清楚是否有某种方法可以让百分比引用父母的父母。

在下面的示例中,我希望文本具有绿色div的宽度,而不是其直接父级的宽度,即白色。



#fluid {
  width: 75vw;
  height: 75vh;
  background: olive;
  position: absolute;
}

#fixed {
  width: 100px;
  height: 100px;
  background: white;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

#text {
  color: black;
  width: 100%;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  margin: 0;
}

<div id="fluid">
  <article id="fixed">
    <h3 id="text">Lorem ipsum dolor sit amet, consectetur adipisicing elit.</h3>
  </article>
</div>
&#13;
&#13;
&#13;

有没有办法只用CSS来实现这个目标?

1 个答案:

答案 0 :(得分:1)

不幸的是,不可能让元素与祖父母的宽度相关直接。但是,您可以将父项作为祖父母的100%,并使目标元素具有其父项的百分比宽度:

#fluid {
  width: 75vw;
}

#fixed {
  width: 100%;
}

#text {
  width: 50% /* 37.5vw */
}

有一个固定宽度的'中间'div和一个与其祖父母相关的孩子很遗憾是不可能的,因为孩子只能与其直接父母相对。

您尝试实现的目标(在典型情况下)的一个解决方案是将#text移出#fixed,并将它们放在绝对位置,#fluid定位相对。它们都会占据相同的区域,产生同样的效果:)

<div id="fluid">
  <article id="fixed"></article>
  <h3 id="text">Lorem ipsum dolor sit amet, consectetur adipisicing elit.</h3>
</div>

#fluid {
  position: relative;
  width: 75vw;
}

#fixed {
  position: absolute;
  width: 100px;
}

#text {
  position: absolute;
  width: 50% /* 37.5vw */
}

虽然听起来好像最终会有多个.article s且只有一个#fluid,但HTML结构可能不合适。

希望这有帮助! :)

相关问题