【问题标题】:Make 50% of div not the browser width [duplicate]使 div 的 50% 不是浏览器宽度 [重复]
【发布时间】:2021-03-03 15:27:28
【问题描述】:

我有.left-navbar.columns-wrapper,其中有两列.left-column.right-column。第一列和第二列有 50% 的 .columns-wrapper,直到我将 position: fixed 添加到 .right-column.right-column 占用浏览器宽度的 50% 而不是 .columns-wrapper

.page-wrapper {
  width: 100vw;
  height: 100%;
  display: flex;
  background: red;
}

.page-wrapper .left-navbar {
  width: 88px;
  height: 100%;
  background: yellow;
}

.page-wrapper .columns-wrapper {
  width: calc(100% - 88px);
  height: 100%;
  background: orange;
  display: flex;
}

.page-wrapper .columns-wrapper .left-column {
  width: 50%;
  height: 100%;
  background: red;
}

.page-wrapper .columns-wrapper .right-column {
  width: 50%;
  height: 100%;
  background: green;
}
<div class="page-wrapper">
  <div class="left-navbar">

  </div>
  <div class="columns-wrapper">
    <div class="left-column"></div>
    <div class="right-column"></div>
  </div>
</div>

【问题讨论】:

  • 拜托,你能编辑你的问题添加一个stackoverflow.com/help/minimal-reproducible-example(最小的可重复示例)
  • The fixed element is removed from the normal document flow, and no space is created for the element in the page layout. It is positioned relative to the initial containing block established by the viewport 来自MDN
  • 那么我应该改变什么

标签: html css


【解决方案1】:

这种行为是完全正常的,因为当您使用 fixed 位置时,该元素将从正常内容流中删除。

#wrapper {
    width: 500px;
    background-color: cyan;
}

.w-1\/2 {
    width: 50%;
    background-color: red;
    height: 100px;
}

.fixed {
    position: fixed;
    width: 50%;
    height: 50px;
    background: yellow;
}
<div id="wrapper">
  <div class="w-1/2">
  </div>
  
  <div class="fixed">
  </div>
</div>

正如您在下面的示例中看到的那样,即使我将其宽度设置为 50%,它也不会占用 #wrapper 的 1/2 空间,而是用于 body 元素。

#wrapper {
    width: 500px;
    background-color: cyan;
}

.w-1\/2 {
    width: 50%;
    background-color: red;
    height: 100px;
}

.fixed {
    position: fixed;
    top: 0;
    left: 50%;
    width: 50%;
    height: 50px;
    background: yellow;
}
<div id="wrapper">
  <div class="w-1/2">
  </div>
  
  <div class="fixed">
  </div>
</div>

【讨论】:

    【解决方案2】:

    columns-wrapper 位置设置为relative,并将left-columnright-column 位置设置为absolute。 绝对位置与位置值为relative的祖先容器有关。

    position: fixed 与整个浏览器位置相关,而不是它的父容器。

    .page-wrapper .columns-wrapper {
      position: relative;
      ...
    }
    
    .page-wrapper .columns-wrapper .left-column {
      position: absolute;
      ...
    }
    
    .page-wrapper .columns-wrapper .right-column {
      position: absolute;
      ...
    }
    

    【讨论】:

    • 我想在右栏添加position: fixed滚动时留在原地
    • .right-columnposition: absolute; 时占 div 的 50%,这很好。但是当我想添加 position: fixed 它需要 50% 的身体而不是 .columns-wrapper
    • 请作为另一个问题提出。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多