admin管理员组文章数量:1391951
I have an HTML structure where labels and inputs are placed inside a div with a grid layout. Here’s my code:
div {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
}
<div>
<span>Label 1</span>
<span><input type="text" placeholder="label 1"></span>
<span>Label 2</span>
<span><input type="text" placeholder="label 2"></span>
<span>Label 3</span>
<span><input type="text" placeholder="label 3"></span>
</div>
I have an HTML structure where labels and inputs are placed inside a div with a grid layout. Here’s my code:
div {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
}
<div>
<span>Label 1</span>
<span><input type="text" placeholder="label 1"></span>
<span>Label 2</span>
<span><input type="text" placeholder="label 2"></span>
<span>Label 3</span>
<span><input type="text" placeholder="label 3"></span>
</div>
The grid works responsively, but since labels and inputs are separate elements, when the screen size changes, they get misaligned.
On large screens, I want 4 columns (Label + Input stays together). On medium screens, I want 2 columns (Label + Input still together). But on some screen sizes, it automatically creates 3 columns, breaking the label-input pair into different lines. Requirement: I don't want 3 columns because it splits labels from their respective inputs. However, I cannot change the HTML structure (e.g., wrapping label and input inside a ).
Question: How can I ensure that each label stays with its corresponding input without changing the HTML structure? Is there a pure CSS solution to enforce only 4, 2, or 1 columns, preventing 3-column layouts?
Share Improve this question edited Mar 13 at 12:08 Ori Drori 194k32 gold badges238 silver badges229 bronze badges asked Mar 13 at 11:29 SmitSmit 334 bronze badges 2 |1 Answer
Reset to default 2When using grid-template-columns
you can state multiple column definitions, each having their own width definition, inside the repeat
:
div {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(75px, 1fr) minmax(150px, 1fr));
}
<div>
<span>Label 1</span>
<span><input type="text" placeholder="label 1"></span>
<span>Label 2</span>
<span><input type="text" placeholder="label 2"></span>
<span>Label 3</span>
<span><input type="text" placeholder="label 3"></span>
</div>
本文标签: htmlHow to Keep Label and Input Together in Responsive CSS Grid LayoutStack Overflow
版权声明:本文标题:html - How to Keep Label and Input Together in Responsive CSS Grid Layout? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744703621a2620706.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
div
as a selector in your CSS can cause no end of trouble. Please tell me you only did that for this question... – KIKO Software Commented Mar 13 at 11:57