Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bootstrap: Input inside a label

In order to avoid having to have an ID for each input element on my form I would like to place my form input inside the label (Bootstrap 3).

My problem is that this is causing extra vertical spacing between rows, the input is not filling the full width of its parent, and the inputs are not aligned.

Illustration

<form class="form-horizontal">
    <div class="form-group">
        <label class="row">
          <span class="col-md-4 control-label">Email:</span>
          <div class="col-md-8">
            <input class="form-control" type="email" placeholder="Email"/>
          </div>
        </label>
    </div>
    <div class="form-group">
        <label class="row">
          <span class="col-md-4 control-label">Password:</span>
          <div class="col-md-8">
            <input class="form-control" type="password" placeholder="Password"/>
          </div>
        </label>
    </div>
</form>
like image 597
Peter Morris Avatar asked May 04 '17 10:05

Peter Morris


People also ask

How do you get labels inside input?

There are two ways to pair a label and an input. One is by wrapping the input in a label (implicit), and the other is by adding a for attribute to the label and an id to the input (explicit). Think of an implicit label as hugging an input, and an explicit label as standing next to an input and holding its hand.

How do you put labels and input on different lines?

Two: [a \/] and so on... then labels are not on the same line as the form fields. Is the only solution: <div><label for="one">One:</label> <input type="text" id="one"></div> ...

Does label go before or after input?

Note that the label is positioned after input elements of type="checkbox" and type="radio" . Note 1: Elements that use explicitly associated labels are: input type="text"

Should I use label for input?

Input fields without accompanying labels can lead to accessibility issues for those who rely on screen readers. If a screen reader comes across an input field without a label it will try to find some accompanying text to use as the label.


1 Answers

The solution is to use the label itself as the form-group, remove the row, and to add a style to the CSS that sets display: block for labels. I have inlined the style in this HTML to show what I mean, obviously you should put it into a CSS.

<form class="form-horizontal">
    <label class="form-group" style="display: block">
      <span class="control-label col-md-2">Email:</span>
      <div class="col-md-10">
        <input class="form-control" type="email" placeholder="Email"/>
      </div>
    </label>
    <label class="form-group" style="display: block">
      <span class="control-label col-md-2">Password:</span>
      <div class="col-md-10">
        <input class="form-control" type="email" placeholder="Email"/>
      </div>
    </label>
</form>
like image 87
Peter Morris Avatar answered Sep 18 '22 00:09

Peter Morris