我有一个带有两个 flexbox 大小的 div 的设置,其中一个我有一个设置为位置固定的标题。我该怎么做才能让它的宽度是父级的 100%?无论宽度如何,它都需要留在父级内部。谢谢。
.block1 {
height: 102.5%;
margin: 0px;
padding: 0px;
flex-basis: 35%;
flex-grow: 1;
flex-shrink: 1;
position: relative;
overflow: scroll;
background-color: white;
outline: solid red 1px;
}
.block2 {
outline: solid red 1px;
height: 102.5%;
margin: 0px;
padding: 0px;
flex-basis: 65%;
flex-grow: 1;
flex-shrink: 1;
position: relative;
overflow: scroll;
background-color: white;
}
.header {
position: fixed;
background-color: red;
width: 100%;
z-index: 2;
}
.container {
width: 100%;
height: 70%;
display: flex;
display: -webkit-box;
display: -moz-box;
display: -ms-flexbox;
display: -webkit-flex;
margin: 0px;
outline: solid blue 1px;
}
<div class="container">
<div class="block1">
<div style="height:200px;">
<div class="header">ff</div>
<div style="height:500px;">
ff
</div>
</div>
</div>
<div class="block2">
<div style="height:200px;">
ff
</div>
</div>
</div>
最佳答案
您需要为 position: fixed
创建一个新的包含 block 元素。默认情况下,使用 position: fixed
将该元素从文档流中拉出,并将其相对于视口(viewport)建立的初始包含 block (即 <body>
)定位。 MDN has a great overview of this property :
The 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, except when one of its ancestors has a transform, perspective, or filter property set to something other than none (see the CSS Transforms Spec), in which case that ancestor behaves as the containing block. (Note that there are browser inconsistencies with perspective and filter contributing to containing block formation.) Its final position is determined by the values of top, right, bottom, and left.
This value always creates a new stacking context. In printed documents, the element is placed in the same position on every page.
我继续更新您的代码片段以说明:
.block1 {
height: 102.5%;
margin: 0px;
padding: 0px;
flex-basis: 35%;
flex-grow: 1;
flex-shrink: 1;
position: relative;
overflow: scroll;
background-color: white;
outline: solid red 1px;
/* Necessary to become containing block for position: fixed child */
transform: translate3d(0, 0, 0);
}
.block2 {
outline: solid red 1px;
height: 102.5%;
margin: 0px;
padding: 0px;
flex-basis: 65%;
flex-grow: 1;
flex-shrink: 1;
position: relative;
overflow: scroll;
background-color: white;
}
.header {
position: fixed;
background-color: red;
width: 100%;
z-index: 2;
}
.container {
width: 100%;
height: 70%;
display: flex;
display: -webkit-box;
display: -moz-box;
display: -ms-flexbox;
display: -webkit-flex;
margin: 0px;
outline: solid blue 1px;
}
<div class="container">
<div class="block1">
<div style="height:200px;">
<div class="header">ff</div>
<div style="height:500px;">
ff
</div>
</div>
</div>
<div class="block2">
<div style="height:200px;">
ff
</div>
</div>
</div>
关于html - 如何使固定位置的 div 继承 flex 大小的父级的宽度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50472555/