[英]Break line after input without html markup
I am trying to display a number of inputs and their corresponding labels. 我试图显示一些输入及其相应的标签。 They are both inline elements, and I have a working solution with adding a br tag at the end like so 它们都是内联元素,我有一个工作解决方案,最后添加一个br标签就像这样
<label for="hello"></label>
<input id="hello" type="text" />
<br>
<label for="stackoverflow"></label>
<input id="stackoverflow" />
Id like to solve this without extraneous HTML markup, ie with CSS. 我喜欢在没有多余HTML标记的情况下解决这个问题,即使用CSS。 What is the easiest way to do this? 最简单的方法是什么?
I have viewed other questions similar to this, but aligning by row instead of by column. 我已经查看了与此类似的其他问题,但是按行而不是按列对齐。
You can wrap the labels around your inputs and display them as blocks: 您可以在输入周围包装标签并将其显示为块:
<style>
label { display: block; }
</style>
<label>
Hello: <input name="hello">
</label>
<label>
StackOverflow: <input name="stackoverflow">
</label>
Note that when you do this you don't need to use the for="name"
attribute. 请注意,执行此操作时,您不需要使用for="name"
属性。
The other way (if you don't want the labels wrapped around your inputs) is to float the labels to the left: 另一种方式(如果你不希望标签缠绕你的输入)是将标签浮动到左边:
<style>
label { float: left; clear: left; }
</style>
However, I generally prefer a little more markup, something that connects the label
and the input
into one logical element, called a field : 但是,我通常更喜欢标记,将label
和input
连接到一个逻辑元素,称为字段 :
<div class="field">
<label for="hello">Hello</label>
<input name="hello">
</div>
<div class="field">
<label for="stackoverflow">Stackoverflow</label>
<input name="stackoverflow">
</div>
Because each field is a div
, it will display as a block automatically, but you can control it for individual fields as well. 因为每个字段都是一个div
,它会自动显示为一个块,但您也可以为各个字段控制它。
Try to set display:inline-block
for your input
and label
elements. 尝试为input
和label
元素设置display:inline-block
。 So you can add all block element specific css like witdh
or margin-bottom
. 因此,您可以添加所有特定于块元素的css,如witdh
或margin-bottom
。
You can also set your input
and label
to display:block
and add margin-bottom
only to the the input. 您还可以设置input
和label
以display:block
并仅将margin-bottom
添加到输入。 Or you can reverse it and add a margin-top to your labels ;) 或者您可以反转它并在标签上添加margin-top;)
If you want to remove the margin on the last element you can use input:last-child {margin-bottom:0;}
如果你想删除最后一个元素的边距,你可以使用input:last-child {margin-bottom:0;}
input, label {display:block;}
input {margin-bottom:18px;}
input:last-child {margin-bottom:0;}
/* Or to be specific you can use the attribut-selector
which only works on inputs with type="text"
*/
input[type="text"]:last-child {margin-bottom:0;}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.