user5182503
user5182503

Reputation:

How to make flex-grow ignore padding?

These are my first steps with flex and I have the following code:

body {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
  font-size: 14px;
}

.flexbox {
  display: flex;
  width: 100%;
  max-width: 1241px;
  height: 30px;
}

label {
  flex-basis: 0;
  flex-grow: 5;
  background-color: cyan;
}

input {
  flex-basis: 0;
  flex-grow: 13;
  background-color: yellow;
  margin: 0;
  padding: 0;
  border: 0;
}

div {
  flex-basis: 0;
  flex-grow: 6;
  height: 10px;
  background-color: red;
}
<div class="flexbox">
  <label>width must = 258.54px</label>
  <input type="text" value="width must = 672.20px">
  <div>width must = 310.25px</div>
</div>

Everything works as expected. However, I need to add to my input padding-left: 25px and as only I do it all sizes of the elements inside flexbox change. How can I add this padding and at the same keep the sizes (I mean using my solution with flex-grow and flex-basis)?

This is what I have with padding:0:

enter image description here

This is what I have when I add padding-left: 25px:

enter image description here

Upvotes: 4

Views: 2437

Answers (2)

Michael Benjamin
Michael Benjamin

Reputation: 370993

How to make flex-grow ignore padding?

flex-grow cannot ignore padding:

  • flex-grow consumes free space.

  • padding occupies space.

  • So flex-grow must factor in padding in order to work properly.

Here's a workaround that may be useful to you:

.flexbox {
  display: flex;
  max-width: 1241px;
  height: 30px;
}

label {
  flex: 5 1 0;
  background-color: cyan;
}

#input {
  flex: 13 1 0;
  height: 100%;
}

input {
  height: 100%;
  width: 100%;
  padding-left: 25px;
  background-color: yellow;
  border: none;
}

div:last-child {
  flex: 6 1 0;
  background-color: red;
}

* {
  box-sizing: border-box;
}

body {
  margin: 0;
  font-size: 14px;
}
<div class="flexbox">
  <label>width must = 258.54px</label>
  <div id="input"><input type="text" value="width must = 672.20px"></div>
  <div>width must = 310.25px</div>
</div>

Upvotes: 4

Temani Afif
Temani Afif

Reputation: 272590

since it's a text input, use text-indent instead of padding:

body {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
  font-size: 14px;
}

.flexbox {
  display: flex;
  width: 100%;
  max-width: 1241px;
  height: 30px;
}

label {
  flex-basis: 0;
  flex-grow: 5;
  background-color: cyan;
}

input {
  flex-basis: 0;
  flex-grow: 13;
  background-color: yellow;
  margin: 0;
  padding: 0;
  border: 0;
}

div {
  flex-basis: 0;
  flex-grow: 6;
  height: 10px;
  background-color: red;
}
<div class="flexbox">
  <label>width must = 258.54px</label>
  <input type="text" value="width must = 672.20px">
  <div>width must = 310.25px</div>
</div>
<div class="flexbox">
  <label>width must = 258.54px</label>
  <input type="text" value="width must = 672.20px" style="text-indent: 25px;">
  <div>width must = 310.25px</div>
</div>

Upvotes: 1

Related Questions