1

I try to use flex layout to make a login content, it's just like an icon and an input in one row. I set width:20px and height:20px with icon and width:100% of input. I think it will make input to cover all the rest width except the specific value. The result is the size of icon changed.

With further learning about flex, I know another ways to achieve, such as flex:1 with input or setting min-width/height of icon, but I just want to know why the width:100% affect size of sibling icon.

.parent {
  width: 72%;
  height: 100px;
  border: 1px solid lightblue;
  display: flex;
  align-items: center;
}

.icon {
  width: 20px;
  height: 20px;
  border: 2px solid green;
  display: block;
}

.login {
  width: 100%;
}

.login::placeholder {
  width: 91px;
}
<div class="parent">
  <div class="icon"></div>
  <input class="login" placeholder="place input your invite code" />
</div>

In this case, the size of .icon became 23.33*24, both width and height changed.

kukkuz
  • 41,512
  • 6
  • 59
  • 95
Aura
  • 33
  • 6
  • 1
    first set `box-sizing: border-box` to take border into the width calculation - now again the width is less than 20px... this is because by default `flex-shrink` value is 1 (`width: 100%` of the input will shrink the `icon`) - so use `flex-shrink: 0` – kukkuz Jun 04 '19 at 03:40

1 Answers1

0

This is due to box-sizing. Your width and height modifications aren't actually coming from flexbox, but rather due to the calculations derived from width: 72% in conjunction with the borders. Note that if you take away the border: 2px solid green on .icon, the .icon height will return to the specified 20px.

If you want to prevent these adjustments, you can set box-sizing: border-box, which will make the .icon's 20px width include all border and padding calculations:

* {
  box-sizing: border: box;
}

I would recommend applying this to all elements with the global selector *, Setting this is often actually recommend due to the fact that it makes element size calculations easier to work with, and in fact this declarations is included by default in most frameworks.

* {
  box-sizing: border-box;
}

.parent {
  width: 72%;
  height: 100px;
  border: 1px solid lightblue;
  display: flex;
  align-items: center;
}

.icon {
  width: 20px;
  height: 20px;
  border: 2px solid green;
  display: block;
}

.login {
  width: 100%;
}

.login::placeholder {
  width: 91px;
}
<div class="parent">
  <div class="icon"></div>
  <input class="login" placeholder="place input your invite code" />
</div>
Obsidian Age
  • 41,205
  • 10
  • 48
  • 71