According to the documentation, flex-basis: 200px
should set the initial size of the item to 200 pixels. However, I find that the initial size is some value between 160 and 170 that seems to depend on the browser, window width (even when it's wider than 200 pixels), and even the amount of margin on the other flexbox items.
<main style="display:flex">
<div style="flex-basis: 200px; background-color: #eee"></div>
<div style="flex-basis: 100%; background-color: #ccc"></div>
</main>
<style>
main, html, body {
position:absolute; top:0; left:0; right:0; bottom:0;
margin: 0;
}
</style>
<script>
for (div of document.getElementsByTagName("div"))
div.innerHTML = "WIDTH=" div.offsetWidth;
</script>
Is there a reliable way to set the initial width of a flexbox item in pixels (assuming there is enough space for that many pixels)?
CodePudding user response:
If you add flex-shrink:0;
this should work as you expect. (If flex-shrink
is not explicitly set, the initial value is 1).
<main style="display:flex">
<div style="flex-basis: 200px; flex-shrink:0; background-color: #eee"></div>
<div style="flex-basis: 100%; background-color: #ccc"></div>
</main>
<style>
main, html, body {
position:absolute; top:0; left:0; right:0; bottom:0;
margin: 0;
}
</style>
<script>
for (div of document.getElementsByTagName("div"))
div.innerHTML = "WIDTH=" div.offsetWidth;
</script>
CodePudding user response:
Your flex-basis
values should be the same ratio that you want them displayed at widths smaller than the total. If you want one element to grow and fill the space give it flex-grow: 1;
. For more info go here: https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Flexible_Box_Layout/Controlling_Ratios_of_Flex_Items_Along_the_Main_Ax
Below, the elements' widths will be 1:2
up to a total width of 600px
then the second element will fill the extra space above that:
<main style="display:flex">
<div style="flex-basis: 200px; background-color: #eee"></div>
<div style="flex-basis: 400px; flex-grow: 1; background-color: #ccc"></div>
</main>
<style>
main, html, body {
position:absolute; top:0; left:0; right:0; bottom:0;
margin: 0;
}
</style>
<script>
for (div of document.getElementsByTagName("div"))
div.innerHTML = "WIDTH=" div.offsetWidth;
</script>