我有这样一种情况,我试图以特定方式设置某些表单元素的样式,但我无法控制 HTML 结构,而且 Javascript 也不是一个选项。我需要一个纯 CSS 解决方案(如果存在的话)。
我想要达到的最终结果是这样的:
O This is the radio button label if
it needs to wrap to the next line.
[There is an optional caption.]
O This is another radio button label.
[There is a caption here]
O Radio Button
O Radio Button
O Radio Button
有问题的 HTML 是 X 系列的单选按钮及其标签。标签在 <span>
内有一个可选的标题(<label>
标签)标签。
<label>
只需要扩展到它包含的内容,所以我一直在使用 display:inline
为了那个原因。这很好用,但如果它延伸到多行,它会包裹在单选按钮下面,这是我想避免的。
O This is the radio button label if
it needs to wrap to the next line. <-- Wraps under radio button
[There is an optional caption.]
O This is another radio button label.
[There is a caption here]
O Radio Button
O Radio Button
O Radio Button
如果我添加 float:left
和 margin-bottom:1em
到单选按钮,然后它就可以工作了。 margin-bottom
导致第二行被正确换行,但仅限于单选按钮的高度加上边距的行数。例如,第三行不会换行。
此外,它要么吹出单行单选按钮:
O Radio Button
Radio Button
O Radio Button
O
或者做得不够, float 堆叠:
O Radio Button
O Radio Button
O Radio Button
同时 float <input>
和 <label>
导致多行出现换行问题,因为现在标签拉伸(stretch)到 100%:
O
This is the radio button label if
it needs to wrap to the next line.
[There is an optional caption.]
O This is another radio button label.
[There is a caption here]
我在这里创建了一个 fiddle :http://jsfiddle.net/qdyr7g83/这显示了我目前所在的位置。
如果我可以控制 HTML,我会把输入和标签放到单独的 div 中并以这种方式控制布局,但我有点受困于我所拥有的东西。有人对此有任何想法吗?我将不得不忍受标签包装吗?
最佳答案
如果您可以使用 calc
( http://caniuse.com/#feat=calc ),给定以下 html:
<div class="container">
<p>Some random text</p>
<input type="radio" id="rdo1" /><label for="rdo1">Some Text Lets make this really long, so long that it wants to wrap to another line. See It is really really long <span>This is a caption. It is also really long and should wrap over atleast one line.</span></label>
<input type="radio" id="rdo2" /><label for="rdo1">Some Text <span>Some Other Text</span></label>
<input type="radio" id="rdo3" /><label for="rdo1">Some Text <span>Some Other Text</span></label>
<input type="radio" id="rdo4" /><label for="rdo1">Some Text <span>Some Other Text</span></label>
</div>
您可以使用以下 CSS:
.container input[type="radio"]
{
display:block;
width:15px;
float:left;
clear:both;
}
.container label
{
display:block;
width:calc(100% - 30px);
float:left;
}
.container label>span
{
display:block;
margin:5px 0;
font-style:italic;
}
关于html - 预定义 HTML 结构中单选按钮、标签和可选标题的 CSS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25879664/