I have multiple buttons inside a flex container (<div class="itemlist">
) and want the last button to have its own row. This flex container itself is inside another flex container (<div class="container">
).
To give the last button its own row, I set flex-basis: 100%;
. Because I don't want the actual button to be that wide, i give it a margin. (I know I could also use a wrapper, but I want to do it without).
A margin of 0 40%
gives the button a width 20%
(= 100% - 2*40%) of the parent container. So far it works as expected. But now I want to give the button a fixed width. Therefore I would logically need to set the margin to 0 calc(50% - wantedWidth/2)
.
When I set the margin of <button class="ownRow">Special Item</button>
using a simple percent or pixel value, it works just fine, but as soon as i use calc to get the value, the parent flex element changes its width to that of my button, which messes things up.
Why is that the case?
Fixed value of margin: 0px 42.3px;
works just fine:
.container {
display: flex;
}
.itemlist {
display: flex;
flex-flow: row wrap;
justify-content: space-around;
}
.ownRow {
/*margin: 0px calc(50% - 50px);*/
margin: 0px 42.3px;
flex-basis: 100%;
}
<div class="container">
<div class="itemlist">
<button>Item 1</button>
<button>Item 2</button>
<button>Item 3</button>
<button>Item 4</button>
<button class="ownRow">Special Item</button>
</div>
</div>
Using margin: 0px calc(50% - 50px);
it doesn't work:
.container {
display: flex;
}
.itemlist {
display: flex;
flex-flow: row wrap;
justify-content: space-around;
}
.ownRow {
margin: 0px calc(50% - 50px);
/* margin: 0px 42.3px; */
flex-basis: 100%;
}
<div class="container">
<div class="itemlist">
<button>Item 1</button>
<button>Item 2</button>
<button>Item 3</button>
<button>Item 4</button>
<button class="ownRow">Special Item</button>
</div>
</div>
This makes no sense for me, because the margin calculated by the browser is the same:
Why is there a different behaviour when using calc() for the margin?