0

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:

enter image description here

Why is there a different behaviour when using calc() for the margin?

FireFuro99
  • 357
  • 1
  • 5
  • 18
  • it's not related to calc() but the use of percentage – Temani Afif Nov 13 '22 at 19:48
  • the duplicate is about padding but the same logic happen with margin – Temani Afif Nov 13 '22 at 19:49
  • @TemaniAfif But with percentage only it works just fine. Try ´margin: 0px 30%;´, works perfectly. https://jsfiddle.net/v0dazpfs/ It only starts to break when you add calc() into the mix. So it IS related to calc(). – FireFuro99 Nov 13 '22 at 20:12
  • 1
    no, it doesn't work like you are expecting. Check this: https://jsfiddle.net/97n814u2/ percentage and pixel doesn't produce the same output. the result get worse if you increase the percentage. – Temani Afif Nov 13 '22 at 20:16

0 Answers0