mik*_*ana 6 css forms css-grid
我input在 CSS 网格容器内有一个元素。容器应该是 100 像素宽,input元素占据大部分空间,一个other-thing占据剩余的 24像素。我正在grid-template-columns为此使用。
如果我将父容器设置为 200 像素而不是 100 像素,这可以正常工作:
.container {
grid-template-columns: 1fr 24px;
grid-template-rows: 1fr;
display: grid;
justify-content: center;
align-items: center;
width: 200px; /* Try 100px */
background-color: red;
}
Run Code Online (Sandbox Code Playgroud)
以及以下 HTML
<div class="container">
<input value="hello"/>
<div class="other-thing">
x
</div>
</div>
Run Code Online (Sandbox Code Playgroud)
但是如果我将容器设置为 100px 宽,输入会突然拒绝缩小 - 所以它与红色容器重叠。
我知道
input元素有一个用户样式表,但我看不到任何与宽度或显示相关的内容,我应该覆盖。
如何input仅使用容器中的剩余空间,最好使用grid-template-columns?
从视觉角度来看,主要问题是justify-content: center。
因为您的容器设置为width: 100px,所以网格项将在该空间内水平居中,在两侧均匀地溢出容器。这会导致左侧消失在屏幕外,并且完全无法访问(即使通过滚动)。
(有关此行为的完整说明,请参阅:无法滚动到溢出容器的弹性项目的顶部)
当您切换到 时width: 200px,容器将获得足够的空间来容纳网格项,因此不会发生溢出。
解决此问题最快、最简单的方法是删除justify-content: center. 无论如何,这是没有意义的,因为容器比内容小,并且容器中没有可用空间就无法将内容居中。所以justify-content什么也不做。
如果您希望所有网格项都适合容器内,请添加min-width: 0到元素中input。这允许input缩小到其内容大小及其min-width: auto默认大小以下。
(有关此行为的完整说明,请参阅:防止内容扩展网格项)
.container {
grid-template-columns: 1fr 24px;
display: grid;
width: 100px;
border: 2px dashed red;
}
input {
min-width: 0;
}Run Code Online (Sandbox Code Playgroud)
<div class="container">
<input value="hello" />
<div class="other-thing">x</div>
</div>Run Code Online (Sandbox Code Playgroud)
请注意,元素的默认宽度和最小宽度input过去可以通过 Chrome / Firefox 检查器工具轻松查看。现在情况似乎不再如此了。我找不到用户代理样式中的设置。我们必须查看计算值作为指导,或者只是假设有宽度和最小宽度设置。