【问题标题】:Percentage width referred to the parent of the parent相对于父级的百分比宽度
【发布时间】:2017-06-11 02:36:02
【问题描述】:

我试图弄清楚是否有某种方法可以使百分比引用父级的父级。

在下面的示例中,我希望文本具有绿色 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>

有什么方法可以让我只使用 CSS 来实现这一点吗?

【问题讨论】:

    标签: html css parent-child percentage


    【解决方案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 */
    }
    

    虽然听起来您最终会拥有多个.articles 而只有一个#fluid,因此HTML 结构可能不适合。

    希望这会有所帮助! :)

    【讨论】:

    • 感谢您的回答 :) 这就是我的想法,但也许使用 rem 单位或类似单位?我对这些不太感兴趣。
    • remem 单位都相对于 font-size。您可以使用它们,但您仍然会面临中间固定容器的问题(remem 始终是相对的):)
    猜你喜欢
    • 2013-06-28
    • 1970-01-01
    • 2015-06-30
    • 2015-09-27
    • 1970-01-01
    • 2012-12-01
    • 2013-02-17
    • 1970-01-01
    相关资源
    最近更新 更多