I have the following html component which essentially adds support for tagging input values. It works as epxected except that it continues to grow passed the width of the parent container. I want it such that it epxands it’s height and grow vertically. The closest I have come to fixing it is by adding the flex-wrap but that always inserts a new line in the input growing it in height even though there is plenty of room still available to the right.
The SO tags input is essentially what I want to recreate:
const input = document.querySelector('.tags > input');
input.addEventListener('keyup', e => {
const container = input.parentNode;
if (e.key === ' ' && input.value.trim().length > 0) {
const button = document.createElement('button');
button.innerText = input.value;
container.insertBefore(button, input);
input.value = '';
}
});
.container {
width: 200px;
}
.tags {
border: 1px solid #777777;
display: flex;
flex-direction: row;
padding: 0.25rem;
}
.tags > input {
background-color: transparent;
border-width: 0;
box-shadow: none;
outline: none;
padding: 0.5rem;
width: 100%;
}
.tags > button:not(:first-child) {
margin-left: 0.1rem;
}
<div class="container">
<div id="tags" class="tags">
<input type="text">
</div>
</div>
>Solution :
The closest I have come to fixing it is by adding the flex-wrap but that always inserts a new line
That’s because you have width: 100% on the input field.
Replace that with flex: 1 1 2em; min-width: 2em – so that it is allowed to grow and shrink as necessary, while keeping a minimum width of 2em (or use a different value, if you like.)
(Red outline added so we can clearly observe the input field’s dimension, feel free to remove that again.)
const input = document.querySelector('.tags > input');
input.addEventListener('keyup', e => {
const container = input.parentNode;
if (e.key === ' ' && input.value.trim().length > 0) {
const button = document.createElement('button');
button.innerText = input.value;
container.insertBefore(button, input);
input.value = '';
}
});
.container {
width: 200px;
}
.tags {
border: 1px solid #777777;
display: flex;
flex-direction: row;
padding: 0.25rem;
flex-wrap: wrap;
}
.tags > input {
background-color: transparent;
border-width: 0;
box-shadow: none;
outline: none;
padding: 0.5rem;
flex: 1 1 2em;
min-width: 2em;
outline: 1px solid red;
}
.tags > button:not(:first-child) {
margin-left: 0.1rem;
}
<div class="container">
<div id="tags" class="tags">
<input type="text">
</div>
</div>
