min-content
and max-content
don't seem to care about the input element's value:
input {
border: 1px solid black;
width: min-content;
}
<input type="text">
min-content
and max-content
don't seem to care about the input element's value:
input {
border: 1px solid black;
width: min-content;
}
<input type="text">
CSS totally ignores the input's value when figuring out min-content, just using some default width that never changes no matter the contents:
How can I make the CSS take the "content" (value) width into account:
Without using javascript to set width
, min-width
or max-width
-
@tacoshy no because the answers very clearly set
width
,min-width
,max-width
– user3310334 Commented Sep 12, 2021 at 21:21 - there are no other answer you can get. CSS has no way in setting the width to fit the content. The only way to do it is through scripting but you obviosly can't set a width of an element if you not allowed to use width. – tacoshy Commented Sep 12, 2021 at 21:26
-
1
Consider using a
contenteditable
element instead. – Sebastian Simon Commented Sep 12, 2021 at 21:28 -
@tacoshy the top answer on the duplicate has a solution to this question: set
size
using JS andwidth: auto;
– user3310334 Commented Sep 12, 2021 at 21:34
2 Answers
Reset to default 5It is not possible without JavaScript.
You have to programmatically set the input's width to the length of its value. This can be simplified with the ch
unit.
document.querySelector('input').addEventListener('input', function() {
this.style.width = this.value.length + 'ch'
})
<input type="text">
You could use this code in the script tag or in the useEffect()
block in React. It will take care for all the input.
Note:
If you want to do it for the specific input tag within a certain div, you might want to use a different CSS selector.
const inputElements = document.querySelectorAll('input');
inputElements.forEach((input) => {
input.style.width = input.value.length + 'ch';
});
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745336593a4623131.html
评论列表(0条)