Home > Net >  Why my third element is not outside of its parent? [duplicate]
Why my third element is not outside of its parent? [duplicate]

Time:10-08

I have the following HTML and css

* {
  box-sizing: border-box;
}

.parent {
  background-color: #001f3f;
  display: flex;
  padding: 20px;
}

.child {
  background-color: #0074d9;
  padding: 20px;
  color: white;
  flex-basis: 50% !important;
  border: 3px solid #4CAF50;
}
<div class="parent">
  <div class="child one">child</div>
  <div class="child two">This is some longer content sdsds ds dssdsdsd sds dsdsdsdsdsd sd sd sds sdsdsdsds sdsdsd sd sd sd sd sdsdsdsdsds sdsdsdsd sds dsdsdsds sdsdsdsdsdsdsd</div>
  <div class="child three">child</div>
</div>

I am saying that the flex items should be 50%. I am having three items, so 3 x 50%, that is 150%. My parent has 100% width, why the third item is fitting inside the parent so I have three equal boxes ?

Only if I set flex-wrap: wrap; on my parent

.parent {
    background-color: #001f3f;
    display: flex;
    padding: 20px;
    flex-wrap: wrap;
}

I get the third items goes into new row, which is expected - because there is no space for the third items here.

Why when I don't specify flex-wrap:wrap and I have by default flex-wrap:no-wrap the items are same inside even I specified 50% width of them

And the flex-grow: is 0 by default ? So they should not grow equally

CodePudding user response:

defaut flex-shrink value is set to 1 , to resize children to fit inside the container on the direction axis set.

If flex-wrap is set to wrap, it won't try to fit the element on single line (or column) but will send element to the next line (or column) .

you need to reset flex-shrink value to 0.

example

* {
  box-sizing: border-box;
}

.parent {
  background-color: #001f3f;
  display: flex;
  padding: 20px;
  
  gap: 20px;/* added to follow your padding idea ? */
  overflow: auto;/* or hidden ? */
}

.child {
  background-color: #0074d9;
  padding: 20px;
  color: white;
  flex-basis: 50%;
  border: 3px solid #4CAF50;
  
  /*added*/
  flex-shrink: 0;
  flex-basis: calc(50% - 10px);/* mind that padding idea ? */
}
<div class="parent">
  <div class="child one">child</div>
  <div class="child two">This is some longer content sdsds ds dssdsdsd sds dsdsdsdsdsd sd sd sds sdsdsdsds sdsdsd sd sd sd sd sdsdsdsdsds sdsdsdsd sds dsdsdsds sdsdsdsdsdsdsd</div>
  <div class="child three">child</div>
</div>

  • Related