如何实现标签居上、输入框居中的行内表单布局?
Fixing Centered Inputs Under Labels with Inline Layout
Hey there! Let's get your form looking exactly how you want it. First off, you've got duplicate id="questions" attributes on your span elements—IDs have to be unique in HTML, so we'll swap those out for a class instead. Then we'll tweak the styling to make sure each input sits centered below its label, while keeping all the form items in an inline row.
Updated CSS
.question-container { width: 1000px; margin: 0 auto; } .question-item { margin: 5px 30px; display: inline-block; text-align: center; /* Centers input and label content horizontally */ } .question-item label { display: block; /* Forces label to take full width of its container */ margin-bottom: 6px; /* Adds space between label and input */ } #centered { text-align: center; /* Keeps submit button centered */ }
Updated HTML
<div class="form-inline"> <span class="question-item"> <label>How much will your house cost?</label> <input class="form-control" type="text" placeholder="input"> </span> <span class="question-item"> <label>What is the most you can pay monthly?</label> <input class="form-control" type="text" placeholder="input"> </span> <span class="question-item"> <label>What is your Current Monthly Rent?</label> <input class="form-control" type="text" placeholder="input"> </span> </div> <div id='centered'> <button type="submit" class="btn btn-primary mb-2">Submit</button> </div>
Key Fixes Explained
- Unique class instead of duplicate IDs: Swapped
id="questions"forclass="question-item"—HTML rules require IDs to be unique across the page. - Centered content per form item:
text-align: centeron.question-itemensures the input sits directly under the center of its label. - Block-level labels: Setting
display: blockon labels makes them occupy the full width of their container, so the input below automatically aligns to the center. - Better spacing: Added small margin between labels and inputs to improve readability, while keeping form items spaced out horizontally.
This setup will keep all your form elements in an inline row, with each input perfectly centered beneath its long label—exactly the effect you're aiming for!
内容的提问来源于stack exchange,提问作者SupremeA
相关产品推荐
相关产品推荐

