【问题标题】:How can I make a fixed positioned div inherit width of parent?如何使固定定位的 div 继承父级的宽度?
【发布时间】:2015-03-14 23:58:54
【问题描述】:

有没有办法固定定位的 div 可以继承父级的宽度?

我知道固定宽度是相对于窗口的,所以这段代码不起作用:

#wrapper{
        position: relative;
        width:500px;
        height: 20px;
        background-color: blue;
}

#header{
        position: fixed;
        width: 100%;
        height: 20px;
        background-color: rgba(255,0,0,0.5);
}
<div id="wrapper">
  #wrapper
        <div id="header">
          #header
        </div>
    </div>

    

【问题讨论】:

    标签: html css width fixed


    【解决方案1】:

    #header 选择器上的width 属性使用inherit 值。

    为什么会这样

    通过将position: fixed 指定给#header 元素,#header 元素的位置是根据指定的视口计算的 在 CSS2 规范中:

    http://www.w3.org/TR/2011/REC-CSS2-20110607/visuren.html#positioning-scheme

    但是,position: fixed 并没有改变 DOM 结构,这意味着 #wrapper 元素仍然是 #header 元素的父元素。作为一个 因此,#header 仍然可以从其父元素继承属性值,即使它的位置是相对于视口确定的。

    另请注意,如果您为宽度指定百分比值,则固定元素将根据视口计算该值,如规范中所述。但是,这与 width: inherit 无关,它的值来自父元素,而不是视口。

    见:http://www.w3.org/TR/2011/REC-CSS2-20110607/visudet.html#propdef-width

    例如,如果您将color 属性添加到#wrapper,它将被#header 继承。

    区别在于width 的初始/默认值是auto,而colorinherit。要获取父级的with属性,需要指定width: inherit,而不是width: 100%

    注意:父元素和包含块之间有细微的区别。在大多数情况下,两者是相同的,但对于固定定位的元素,它们是不同的。

    #wrapper {
      position: relative;
      width: 500px;
      height: 20px;
      background-color: blue;
      color: white;  /* for demo */
    }
    #header {
      position: fixed;
      width: inherit;
      height: 20px;
      background-color: rgba(255, 0, 0, 0.5);
    }
    <div id="wrapper">
      #wrapper
      <div id="header">
        #header
      </div>
    </div>

    【讨论】:

    • @Morpheus 好问题,我正在查找 CSS 规范以找出它为什么有效,但并不明显。
    • 谢谢,真的很有用
    • 如果它帮助你解决了你的问题,记得给答案投票。欢迎使用 StackOverflow!
    • @MarcAudet 有什么发现吗?
    • @Morpheus 我在原始答案中添加了更多细节,可以更清楚地解释事情。
    【解决方案2】:

    改变

    #wrapper{
        position: relative;
        width:500px;
    }
    

    #wrapper{
        position: absolute;
        width:500px;
    }
    

    【讨论】:

    • 我知道“绝对”会使其相对于父级,但我需要对其进行修复,以便在用户向下滚动时它不会消失。
    猜你喜欢
    • 1970-01-01
    • 2018-11-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-03
    • 1970-01-01
    • 1970-01-01
    • 2017-06-03
    相关资源
    最近更新 更多