将固定div设置为父容器的100%宽度

Jac*_*och 81 html css

我有一个带有一些填充的包装器,然后我有一个浮动的相对div,其百分比宽度(40%).

在浮动相对div内部,我有一个固定的div,我希望它的大小与其父级相同.我知道固定div从文档流中删除,因此忽略了包装器的填充.

HTML

<div id="wrapper">
  <div id="wrap">
    Some relative item placed item
    <div id="fixed"></div>
  </div>
</div>
Run Code Online (Sandbox Code Playgroud)

CSS

body { 
  height: 20000px 
}  
#wrapper {
  padding: 10%;
}  
#wrap { 
  float: left;
  position: relative;
  width: 40%; 
  background: #ccc; 
} 
#fixed { 
  position: fixed;
  width: inherit;
  padding: 0px;
  height: 10px;
  background-color: #333;
}
Run Code Online (Sandbox Code Playgroud)

这是必须的小提琴:http://jsfiddle.net/C93mk/489/

有谁知道这样做的方法?

我已经修改了小提琴,以显示我想要完成的更多细节,对于这种混淆感到遗憾: http ://jsfiddle.net/EVYRE/4/

YD1*_*D1m 40

你可以使用.wrap容器的margin而不是.wrapper的padding:

body{ height:20000px }
#wrapper { padding: 0%; }
#wrap{ 
    float: left;
    position: relative;
    margin: 10%;
    width: 40%; 
    background:#ccc; 
}
#fixed{ 
    position:fixed;
    width:inherit;
    padding:0px; 
    height:10px;
    background-color:#333;    
}
Run Code Online (Sandbox Code Playgroud)

的jsfiddle

  • `width:inherit`是我代码的神奇之处......谢谢! (7认同)
  • 它并没有真正起作用,看看这个小提琴http://jsfiddle.net/EVYRE/4/.#sidebar宽度将相对于他的父级(#sidebar_wrap),但它不是,并且它溢出了他的父级. (5认同)

小智 5

尝试向父级添加转换(不必做任何事情,可能是零转换)并将固定子级的宽度设置为 100%

body{ height:20000px }
#wrapper {padding:10%;}
#wrap{ 
    float: left;
    position: relative;
    width: 40%; 
    background:#ccc; 
    transform: translate(0, 0);
}
#fixed{ 
    position:fixed;
    width:100%;
    padding:0px;
    height:10px;
    background-color:#333;
}
Run Code Online (Sandbox Code Playgroud)
<div id="wrapper">
    <div id="wrap">
    Some relative item placed item
    <div id="fixed"></div>
    </div>
</div>
Run Code Online (Sandbox Code Playgroud)