I am trying to create a margin that disappears as the viewport becomes smaller, while the main content remains the same size as long as possible. This margin is supposed to have a maximum size, so using auto
is out of the question.
In other terms, my question is how to control the shrink priority of different items on the website.
The Flexbox model allows to set the ratio of shrinkage, but not the order of it.
Which options, not using Javascript, do I have to achieve this?
Note: I'm answering my own question here but I'm also looking for better answers.
flex-shrink
/flex-grow
One way is to have one flexbox item flex-shrink
, and to have the other grow to the size it should have with flex-grow
. This way, the latter item will 'shrink' (decrease its growth) first.
More than two levels can be achieved by nesting this construction.
.flex-container {
display: flex;
}
.first-to-shrink {
flex-shrink: 0;
flex-grow: 1;
flex-basis: 0px;
min-width: 0px;
background: coral;
}
.second-to-shrink {
flex-shrink: 1;
flex-grow: 0;
background: cornflowerblue;
}
<div class="flex-container">
<div class="first-to-shrink flex-container">
<div class="first-to-shrink">
This is going to shrink first!
</div>
<div class="second-to-shrink">
And then this one is going to shrink!
</div>
</div>
<div class="second-to-shrink flex-container">
<div class="first-to-shrink">
This one is going next!
</div>
<div class="second-to-shrink">
This is the last one to disappear!
</div>
</div>
</div>
Another way is to calculate the size for each item as the difference of the viewport and the size of all other items that should shrink after it (this requires knowing the size of each of them), as follows:
.shrinkable {
overflow: hidden;
max-height: 100px;
}
#first-to-shrink {
height: calc(100vh - 300px);
background: coral;
}
#second-to-shrink {
height: calc(100vh - 200px);
background: cornflowerblue;
}
#third-to-shrink {
height: calc(100vh - 100px);
background: coral;
}
#fourth-to-shrink {
height: 100vh;
background: cornflowerblue;
}
<div id="first-to-shrink" class="shrinkable">
This is going to shrink first!
</div>
<div id="second-to-shrink" class="shrinkable">
And then this one is going to shrink!
</div>
<div id="third-to-shrink" class="shrinkable">
This one is going next!
</div>
<div id="fourth-to-shrink" class="shrinkable">
This is the last one to disappear!
</div>