Issue
Why does the .content
element have some extra space when I set the .input-field
to have a width
of 20%
and input
to have a width
of 100%
? and when I remove the width: 20%
on the .content
. the input takes up the extra space and doesn’t have that issue anymore. (I wanted to restrict the width of input so I added the width:20%
on the .input-field
.
*{
margin:0;
padding: 0;
box-sizing: border-box;
}
.parent {
display: flex;
flex-direction: column;
}
.content:nth-child(1) {
display: flex;
align-self: flex-end;
}
input {
width: 100%;
}
.input-field {
display: flex;
justify-content: space-between;
align-items: center;
width: 20%;
min-width: 10rem;
max-width: 20rem;
}
label {
margin-right: 0.5rem;
}
<div class="parent">
<div class="content">
<div class="input-field">
<label>hey</label>
<input type="text" />
</div>
</div>
<div class="content"><p>hey</p></div>
<div class="content"><p>you</p></div>
</div>
Solution
Percentages are relative to the parent element. When you give 20%
to the .input-field
it would be relative to the parent .ie., the .content
so it is occupying 20% of .content
but it is lower than the min width so it is falling back to min-width: 10rem
and leaving an empty space at the end since even 10rem
is less than 100% of .content
. If you don’t want the extra space you can:
- Set
width:min-content
to.content
so it does just occupies then intrinsic minimum width of the content which is kind of awkward. - Set
width:100%
to.input-field
and control the size of its parent.content
.
<style>
.content {
width: min-content;
}
*{
margin:0;
padding: 0;
box-sizing: border-box;
}
.parent {
display: flex;
flex-direction: column;
}
.content:nth-child(1) {
display: flex;
align-self: flex-end;
}
input {
width: 100%;
}
.input-field {
display: flex;
justify-content: space-between;
align-items: center;
width: 20%;
min-width: 10rem;
max-width: 20rem;
}
label {
margin-right: 0.5rem;
}
</style>
<div class="parent">
<div class="content">
<div class="input-field">
<label>hey</label>
<input type="text">
</div>
</div>
<div class="content"><p>hey</p></div>
<div class="content"><p>you</p></div>
</div>
Answered By – deepakchethan
This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0