最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - CSS width of input element's contents. min-content doesn't work for inputs - Stack Overflow

programmeradmin1浏览0评论

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

Share Improve this question asked Sep 12, 2021 at 21:15 user3310334user3310334 4
  • @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 and width: auto; – user3310334 Commented Sep 12, 2021 at 21:34
Add a ment  | 

2 Answers 2

Reset to default 5

It 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';
});
发布评论

评论列表(0)

  1. 暂无评论