设置固定块相对于父 div(容器)的宽度



我有一个container,里面我有一个position:fixed块。我需要这个块的宽度是容器大小的 40%。
问题是,当您将position:fixed应用于块时,宽度不再是相对于父块,而是相对于屏幕大小。

我无法用percentpx来解决这个问题,因为它会在某些设备上制动布局。

我正在使用Twitter-Bootstrap的容器类

您可以使用

width: inherit;继承父div 的宽度。

在此示例中,我创建了一个具有固定位置并继承其父级宽度的容器。在这个固定容器中,还有另一个div 的宽度为固定容器的 40%。

.container {
  width: 400px;
  height: 40px;
  background-color: #0000ff;
}
.container-fixed {
  position: fixed;
  height: 30px;
  width: inherit;
  background-color: #ff0000;
}
.container-fixed-inner {
  width: 40%;
  height: 20px;
  background-color: #00ff00;
}
<div class="container">
  <div class="container-fixed">
    <div class="container-fixed-inner">
      <span>Some text</span>
    </div>
  </div>
</div>

最新更新