Html 使用纯 CSS 使单选组标签与单选按钮很好地内联显示
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21713819/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Make radio group labels display nicely inline with radio buttons using pure CSS
提问by broinjc
Previously I used a table to display radio buttons with labels. Now I am trying to do this same thing using only CSS.
以前我使用表格来显示带有标签的单选按钮。现在我正在尝试只使用 CSS 来做同样的事情。
What can I do in CSS that will make the label text sit nicely on top of the related radio button? This is the HTML:
我可以在 CSS 中做什么才能使标签文本很好地位于相关单选按钮的顶部?这是 HTML:
<div class="controls">
<label class="radio">
<input type="radio" name="cfimb_5" id="id_cfimb_5_1" value="1">
Never
</label>
<label class="radio">
<input type="radio" name="cfimb_5" id="id_cfimb_5_2" value="2">
</label>
<label class="radio">
<input type="radio" name="cfimb_5" id="id_cfimb_5_3" value="3">
Sometimes
</label>
<label class="radio">
<input type="radio" name="cfimb_5" id="id_cfimb_5_4" value="4">
</label>
<label class="radio">
<input type="radio" name="cfimb_5" id="id_cfimb_5_5" value="5">
Frequently
</label>
</div>
Here is a codepen: http://codepen.io/anon/pen/keuhl
这是一个代码笔:http://codepen.io/anon/pen/keuhl
回答by Nit
Historically, you could use margins to achieve this layout:
从历史上看,您可以使用边距来实现这种布局:
.controls label {
display: inline-block;
width: 90px;
height: 20px;
text-align: center;
vertical-align: top;
padding-top: 40px;
}
.controls input {
display: block;
margin: 0 auto -40px;
}
<div class="controls">
<label class="radio">
<input type="radio" name="foo" value="1">
Never
</label>
<label class="radio">
<input type="radio" name="foo" value="2">
</label>
<label class="radio">
<input type="radio" name="foo" value="3">
Sometimes
</label>
<label class="radio">
<input type="radio" name="foo" value="4">
</label>
<label class="radio">
<input type="radio" name="foo" value="5">
Frequently
</label>
</div>
On modern browsers that support flexbox, the solution is considerably easier:
.controls {
display: flex;
}
.radio {
flex: 1 0 auto;
display: flex;
flex-direction: column;
align-items: center;
}
<div class="controls">
<label class="radio">
<input type="radio" name="foo" value="1">
Never
</label>
<label class="radio">
<input type="radio" name="foo" value="2">
</label>
<label class="radio">
<input type="radio" name="foo" value="3">
Sometimes
</label>
<label class="radio">
<input type="radio" name="foo" value="4">
</label>
<label class="radio">
<input type="radio" name="foo" value="5">
Frequently
</label>
</div>