Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
681 views
in Technique[技术] by (71.8m points)

html - How can I make a fixed positioned div inherit width of parent?

Is there a way a fixed positioned div can inherit the width of a parent?

I know fixed width is relative to the window's so this code doesn't work:

#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>

    
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use the inherit value for the width property on the #header selector.

Why This Works

By specifying position: fixed to the #header element, the #header element's position is calculated with respect to the viewport as specified in the CSS2 specification:

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

However, position: fixed does not change the DOM structure, which means that the #wrapper element is still the parent of the #header element. As a consequence, the #header can still inherit property values from its parent element, even though its position is determined with respect to the viewport.

Note also that if you specify a percentage value for the width, the fixed element will calculate the value based on the viewport, as stated in the specification. However, this does not pertain to width: inherit, which takes its value from the parent element, not the viewport.

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

For example, if you added the color property to #wrapper, it would be inherited by #header.

The distinction is that the initial/default value for width is auto whereas for color it is inherit. To get the parent's with property, you need to specify width: inherit, not width: 100%;

Note: There is a subtle distinction between the parent element and the containing block. In most cases, the two are the same, but for fixed positioned elements, they are different.

#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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.8k users

...