The form has a fixed width of 300px with a grid layout. I have made it two columns by
grid-template-columns: repeat(2, 1fr)
, and I have also tried grid-template-columns: auto auto
, but the elements are still going outside of the form.
How to make the elements auto-adjust their width to suit the form width?
form {
display: grid;
grid-template-columns: repeat(2, 1fr);
gap: 30px;
background-color: green;
width: 300px;
}
textarea {
grid-column: span 2 / span 2;
}
<form>
<input placeholder="First Name" type="text" name="first_name" required>
<input placeholder="Last Name" type="text" name="last_name" required>
<textarea placeholder="Message" name="message" rows="5"></textarea>
<input type="submit" value="Submit">
</form>
CodePudding user response:
1fr
means minmax(auto, 1fr)
which is a well-known concern here. In your context, auto
is not obvious, and that causes unexpected widths for your input fields.
To fix it, you should set grid-template-columns: repeat(2, minmax(0, 1fr));
instead.
form {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 30px;
background-color: green;
width: 300px;
}
textarea {
grid-column: span 2 / span 2;
}
<form>
<input placeholder="First Name" type="text" name="first_name" required>
<input placeholder="Last Name" type="text" name="last_name" required>
<textarea placeholder="Message" name="message" rows="5"></textarea>
<input type="submit" value="Submit">
</form>
CodePudding user response:
You will need to set the overflow of any child elements to a value other than the default of visible.
form input {
overflow: hidden; // New
}
form {
display: grid;
grid-template-columns: repeat(2, 1fr);
grid-auto-rows: minmax(min-content, max-content);
gap: 30px;
background-color: green;
width: 300px;
}
textarea {
grid-column: span 2 / span 2;
}
<form>
<input placeholder="First Name" type="text" name="first_name" required>
<input placeholder="Last Name" type="text" name="last_name" required>
<textarea placeholder="Message" name="message" rows="5"></textarea>
<input type="submit" value="Submit">
</form>