代码之家  ›  专栏  ›  技术社区  ›  Misha Moroshko Amr Mostafa

如何为固定的子级实现100%父级宽度?[副本]

  •  1
  • Misha Moroshko Amr Mostafa  · 技术社区  · 8 年前

    这个问题已经有了答案:

    运行下面的代码片段,看看我要实现什么。

    主要问题是:如果没有javascript,这是否可能实现?

    .container {
      display: flex;
      width: 400px;
      height: 2000px;
      background-color: #aaa;
    }
    
    .left {
      width: 150px;
      background-color: lightgreen;
    }
    
    .right {
      width: 100%;
      background-color: lightcoral;
    }
    
    .fixed {
      position: fixed;
      height: 100px;
      width: 100%;
      background-color: skyblue;
    }
    <div class="container">
      <div class="left">
        My width can change anytime.
      </div>
      <div class="right">
        <div class="fixed">
          I'm fixed. Scroll the page to verify.<br /> I want to be the same width as my red parent.<br /> Any tips?
        </div>
      </div>
    </div>
    1 回复  |  直到 8 年前
        1
  •  0
  •   Mr Lister hawi    8 年前

    实际上,您可以根据flex项的宽度计算它需要的宽度。

    左项的宽度为150px,右项的宽度为100%(解析为400px)。这总计550px,并挤入400px flex容器,因此正确项目的实际使用宽度为400px*(400/550)。
    (当然,这是在没有任何扭曲因素的情况下进行的,如flex grow,这将使整个计算更加复杂!)

    .container {
      display: flex;
      width: 400px;
      height: 2000px;
      background-color: #aaa;
    }
    
    .left {
      width: 150px;
      background-color: lightgreen;
    }
    
    .right {
      width: 100%;
      background-color: lightcoral;
      position:relative;
      
    }
    
    .fixed {
      position: fixed;
      height: 100px;
      background-color: skyblue;
      width:calc(400px * (400 / (400 + 150)));
    }
    <div class="container">
      <div class="left">
        My width can change anytime.
      </div>
      <div class="right">
        <div class="fixed">
          I'm fixed. Scroll the page to verify.<br > I want to be the same width as my red parent.<br > Any tips?
        </div>
      </div>
    </div>