Why do form-groups have a negative margin in Bootstrap?

Why do form-groups have a negative margin in Bootstrap?

I have this very simple code using Bootstrap 3:



and it appears like this:

Notice how tho labels and the inputs are sticking to the left. Inspecting those elements I found this:
.form-horizontal .form-group {
margin-left: -15px;
margin-right: -15px;
}

Why is that there? I know it’s trivial to remove, but it makes me wonder whether the way I’m using Bootstrap is wrong. How should I use it?

Solutions/Answers:

Solution 1:

It’s happening because you are using form-horizontal which is meant to be used as a row along with col-*‘s for layout. From the Bootstrap docs:

Use Bootstrap’s predefined grid classes to align labels and groups of form controls in a horizontal layout by adding .form-horizontal to the form (which doesn’t have to be a <form>). Doing so changes .form-groups to behave as grid rows, so no need for .row.

So if you simply remove the form-horizontal the negative margin goes away.

Related:  Bootstrap Carousel with dynamic items does not slide

http://codeply.com/go/QQnqgfKv9v

Solution 2:

I just spend some time getting to understand this negative margin as well.
Turns out that normally you embed a form-horizontal into a container or container-fluid that puts a margin of 15px and the form-groups use -15px.

The real problem is that you are missing some <div class="col-..."> to wrap your label and form controls.

These add some padding left+right and that will display it correctly.

Something like:

<html>
  <body>
    <main class="container" role="main">
      <form class="simple_form form-horizontal">
        <div class="form-group text required campaign_url">
          <div class="col-md-12">
            <label class="text required control-label" for="campaign_url"><abbr title="required">*</abbr> Url</label>
          </div>
          <div class="col-md-12">
            <textarea class="text required form-control col-md-12" name="campaign[url]" id="campaign_url"></textarea>
          </div>
        </div>

References