如何防止单选按钮与其标签之间的换行,同时仍允许标签内的换行?

mik*_*ike 19 html css

我想确保单选按钮和相邻标签的开头之间永远不会有换行符.但是,我希望允许标签的文本换行.这可能吗?您可以通过呈现以下HTML来查看我失败的尝试:

<html>
 <head>
   <style type="text/css">
.box {
  border: solid gray 2px;
  width: 200px;
  margin: 5px;
}
.chopped {
  overflow: hidden;
}
   </style>
 </head>
<body>
Run Code Online (Sandbox Code Playgroud)

这些盒子需要固定宽度,因此需要包裹很长的内容,如下面的第一个框所示.如果有人试图发布一个没有任何空格的可笑长字符串,我们需要将其截断,而不是延伸到框的边缘 - 问题在第二个框中可见:

 <div class="box">
  <input type="radio"/>
  <label>This is a really long string with no spaces</label>
 </div>

 <div class="box">
  <input type="radio"/>
  <label>This_is_a_really_long_string_with_no_spaces</label>
 </div>

 <hr/>
Run Code Online (Sandbox Code Playgroud)

所以我添加"overflow:hidden",事情稍微好一点,但我仍然不喜欢第二个框在单选按钮和它的标签之间有换行符:

 <div class="chopped box">
  <input type="radio"/>
  <label>This is a really long string with no spaces</label>
 </div>

 <div class="chopped box">
  <input type="radio"/>
  <label>This_is_a_really_long_string_with_no_spaces</label>
 </div>

 <hr/>
Run Code Online (Sandbox Code Playgroud)

如果我添加<nobr>,单选按钮就在它们的标签旁边,因此未空格的字符串现在看起来很完美.但是,这会破坏第一个字符串(带空格的字符串),因为它不再包装:

 <div class="chopped box">
  <nobr>
    <input type="radio"/>
    <label>This is a really long string with no spaces</label>
  </nobr>
 </div>
 <div class="chopped box">
  <nobr>
    <input type="radio"/>
    <label>This_is_a_really_long_string_with_no_spaces</label>
  </nobr>
 </div>

</body>
</html>
Run Code Online (Sandbox Code Playgroud)

Jac*_*son 43

首先,移动标签内的单选按钮.这增加了一个很好的功能,您可以通过单击文本选择单选按钮.然后在文本周围添加一个范围.

<div class="chopped box">
 <label>
  <input type="radio"/>
  <span class="wrappable">This is a really long string with no spaces</span>
 </label>
</div>

<div class="chopped box">
 <label>
  <input type="radio"/>
  <span class="wrappable">This_is_a_really_long_string_with_no_spaces</span>
 </label>
</div>
Run Code Online (Sandbox Code Playgroud)

其次,将以下样式添加到您的css:

label {
    white-space:nowrap;
}

.wrappable {
    white-space:normal;
}
Run Code Online (Sandbox Code Playgroud)

标签上的白色空间样式可防止单选按钮和文本之间的换行符,文本周围的跨度允许它在文本中进行换行.

  • 您可以通过为*id定义标签*来更轻松地单击标签来选择radion按钮,例如="ID_of_radio_button"的标签 (3认同)