i have a flex container that contains 2 divs
, one of them is fixed, I want the other one to act just like its not fixed ( respect its width ), how to do that ?
<div >
<div style="position:fixed; width:15%;">...</div>
<div style="width:85%">...</div> // starts from the beginning of the page and ignores the width of the upper div becuase its fixed
</div>
CodePudding user response:
Layout wise there is no reason to put something fixed inside flexbox. Usual design pattern would be to use padding to offset things so that they wouldnt be covered by fixed position element with known dimensions.
That said solution to what you are asking without using padding would be to wrap you fixed element in dummy element with correct size.
html, body {padding: 0; margin: 0}
.container {
height: 2000px;
display: flex;
}
.element-fixed {
position: fixed;
background-color: red;
width: 15%;
}
.element1 {
height: 300px;
flex: 0 0 15%;
}
.element2 {
height: 200px;
background-color: blue;
flex: 0 0 85%;
}
<div >
<div class='element1'>
<div >...</div>
</div>
<div class='element2'>...</div>
</div>
But here is a lot easier way to do it with padding.
html, body {margin: 0; padding: 0;}
.container {
padding-left: 15%;
display: flex;
height: 2000px;
}
.fixed {
position: fixed;
background-color: red;
height: 200px;
width: 15%;
margin-top: 10px;
}
.element1 {
flex: 0 0 100%;
background-color: blue;
height: 200px;
}
<div >...</div>
<div >
<div >...</div>
</div>
Also position: sticky;
can be something you might want to look into depending on what you are trying to do.
CodePudding user response:
You set the flex-grow and flex-shrink to 0 for the fixed item and set a fixed width to it. You set the flex-grow and flex-shrink to 1 (or greater) for the variable-width container and that one will grow and shrink in preference to the first one. You can use the flex: rule as a shorhand for this.
.container {
display: flex;
}
.fixed-width {
flex: 0 0 auto;
width: 100px;
}
.variable-width {
flex: 1 1 auto;
}
.container div {
border: 1px solid red;
}
<div >
<div class='fixed-width'>This is fixed</div>
<div class='variable-width'>This is variable width</div>
</div>