1
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <title>My CSS experiment</title>
    <link rel="stylesheet" href="styles.css" />
  </head>

  <body>
    <div class="box">
      <div>One</div>
      <div>Two</div>
      <div>Three</div>
    </div>
  </body>
</html>

css file:

.box {
  width: 300px;
  height: 300px;
  border: 5px dotted lightcoral;
  display: flex;
}

.box div {
  width: 200px;
  height: 100px;
  border: 1px solid red;
}

here the width of the flex items is more than the flex container size but still the items do not overflow on the main axis. When I inspect the element I notice that the width of the flex items is 100px, but i have given them a width of 200px. So why is browser not giving the flex items a width of 200px?

The link I am following is : https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Flexible_Box_Layout/Basic_Concepts_of_Flexbox

Johannes
  • 64,305
  • 18
  • 73
  • 130
tin_tin
  • 478
  • 3
  • 10
  • 24

2 Answers2

3

If you add flex-shrink: 0; to the flex items to prevent their automatic shrinking, they keep their defined width , causing an overflow.

.box {
  width: 300px;
  height: 300px;
  border: 5px dotted lightcoral;
  display: flex;
}

.box div {
  width: 200px;
  height: 100px;
  border: 1px solid red;
  flex-shrink: 0;
}
<div class="box">
  <div>One</div>
  <div>Two</div>
  <div>Three</div>
</div>
Johannes
  • 64,305
  • 18
  • 73
  • 130
2

From the tutorial you linked:

The live sample below contains items that have been given a width, the total width of the items being too wide for the flex container. As flex-wrap is set to wrap, the items wrap. Set it to nowrap, which is also the initial value, and they will instead shrink to fit the container because they are using initial flexbox values that allows items to shrink.

thingEvery
  • 3,368
  • 1
  • 19
  • 25
  • okay i understand there are some initial values set..later in the article it says flex-shrink defaults to 1. may be that is the reason. – tin_tin Jan 01 '20 at 16:05
  • 1
    @tin_tin Yup, you haven't set the `flex-wrap` attribute so it's defaulting to `nowrap`, which is causing it to ignore your `width` values. Note, if you set the `width` to a value small enough to fit inside the outer div, they would not stretch beyond that value. BTW, if this answers your question, please hit the check mark for me. – thingEvery Jan 01 '20 at 16:12