2

I'm trying to make a new layout when I encountered this behaviour where the computed width is different from the specified width. So now, I'm curious on the way the width is computed in this scenario.

I know I can use .row-1 { width: calc(100% - 70px); } so row-2 will have 70px width, but I want to know how width: 100% works with px width in this case.

I expect the width of row-2 to be 70px, but the computed value is somewhere in between 60px - 69px.

html,
body {
  width: 100%;
}

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

.container {
  display: flex;
  width: 100%;
}

.row {
  border: 1px solid black;
  padding: 5px;
}

.row-1 {
  width: 100%;
}

.row-2 {
  width: 70px;
}
<html>
  <body>
    <div class="container">
      <div class="row row-1">row 1</div>
      <div class="row row-2">row 2</div>
    </div>
  </body>
</html>

EDIT: The last sentence may be confusing as to what my inquiry is about. What I want to know is the way the browser computes the width of row-2 in this scenario. Why is it not 70px like the specified width?

kukkuz
  • 41,512
  • 6
  • 59
  • 95
nubimi
  • 21
  • 4
  • your row are flex elements , if i remember it has default flex:0 1 auto. It means : _It makes the flex item inflexible when there is some free space left, but allows it to shrink to its minimum when there is not enough space_ – Sfili_81 May 15 '19 at 07:46
  • Yes @Sfili_81, it has a default `flex: 0 1 auto`. But, do you happen to know how `row-2` width is computed to `60px`+ instead of `70px`? – nubimi May 15 '19 at 08:26
  • because row 2 need 60px to show it's content – Sfili_81 May 15 '19 at 10:12
  • flex-shrink:0 to the elements and you will see (100% + 70px > 100% so the elements will shrink equally by the extra 70px ) – Temani Afif May 15 '19 at 10:15

1 Answers1

2

Instead us width use flex:1 0 ...

html,
body {
  width: 100%;
}

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

.container {
  display: flex;
  width: 100%;
}

.row {
  border: 1px solid black;
  padding: 5px;
}

.row-1 {
     flex: 0 1 100%;
}

.row-2 {
     flex: 1 0 70px;
}
<html>
  <body>
    <div class="container">
      <div class="row row-1">row 1</div>
      <div class="row row-2">row 2</div>
    </div>
  </body>
</html>
לבני מלכה
  • 15,925
  • 2
  • 23
  • 47
  • That's a good solution. But, I want to know how `row-2` got a width of `60px`+ instead of `70px` in my post. – nubimi May 15 '19 at 08:29
  • 2
    Flexbox items have flex-shrink parameter with default of 1. This means that in case your flexbox container don't have enough space its items will shrink.:https://www.w3schools.com/cssref/css3_pr_flex-shrink.asp – לבני מלכה May 15 '19 at 08:37