I have an input
element, inside a CSS grid container. The container should be 100 pixels wide, with the input
element taking up most of the space, and an other-thing
taking up the remaining 24px. I am using grid-template-columns
for this.
This works fine if I make the parent container 200px instead of 100px:
.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;
}
And the following HTML
<div class="container">
<input value="hello"/>
<div class="other-thing">
x
</div>
</div>
But if I make the container 100px wide, the input suddenly refuses to shrink - so it overlaps the red container.
I know
input
elements have a user stylesheet, but I can't see anything related to width or display there that I should be overriding.
Here is a jsfiddle
How do I make the input
only use the remaining space in the container, preferably using grid-template-columns
?
.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>
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With