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
<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, i.e with 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.
Note: Use the <br> tag to enter line breaks, not to add space between paragraphs.
Instead of using the <br> tag, you should use a semantic HTML element and the CSS margin or padding properties if necessary.
You can insert line breaks in HTML with the <br> tag, which is equivalent to a carriage return on a keyboard. Be aware that HTML will ignore any line break from a keyboard's return key.
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.
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:
<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.
Try to set display:inline-block
for your input
and label
elements. So you can add all block element specific css like witdh
or margin-bottom
.
You can also set your input
and label
to display:block
and add margin-bottom
only to the the input. Or you can reverse it and add a margin-top to your labels ;)
If you want to remove the margin on the last element you can use 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;}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With