How can I make an input element respect the dimensions of a grid container?

前提是你 提交于 2019-12-05 18:24:08

The main problem, from a visual perspective, is justify-content: center.

Because your container is set to width: 100px, the grid item will center horizontally within that space, overflowing the container equally on both sides. This causes the left side to disappear off-screen, and become totally inaccessible (even via scroll).

(For a full explanation of this behavior, see: Can't scroll to top of flex item that is overflowing container)

When you switch to width: 200px, the container is given enough space to accommodate the grid items, so the overflow doesn't occur.

The quickest and easiest solution to this problem is to remove justify-content: center. It's pointless anyway because the container is smaller than the content, and you can't center content without free space in the container. So justify-content isn't doing anything.

If you want all grid items to fit inside the container, then add min-width: 0 to the input element. This allows the input to shrink below the size of its content and its min-width: auto default.

(For a full explanation of this behavior, see: Prevent content from expanding grid items)

.container {
  grid-template-columns: 1fr 24px;
  display: grid;
  width: 100px;
  border: 2px dashed red;
}

input {
  min-width: 0;
}
<div class="container">
  <input value="hello" />
  <div class="other-thing">x</div>
</div>

Note that the default width and minimum width of input elements used to be easy to see via Chrome / Firefox inspector tools. This appears to no longer be the case. I couldn't find the settings in user agent styles. We have to look at computed values for guidance or just assume there are width and min-width settings.

.container {
  display: grid;
  grid-template-columns: 1fr 24px;
  width: 100px;
  background-color: red;
}

input {
  min-width: 0;
}
<div class="container">
  <input value="hello" />
  <div class="other-thing">
    x
  </div>
</div>
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!