javascripthtmltwitter-bootstrapbootstrap-5

Bootstrap "form-floating": label has weird margins when inside "row"


I'm trying to use form-floating to get the floating label look, but the margins get messed up when I put the form-floating class inside a row.

For comparison, this is without the row (label looks good):

<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet"/>

<div class="container">
  <div class="form-floating col-6 mb-3 mt-3 ml-auto">
    <input type="text" class="form-control" id="name">
    <label for="name">Name</label>
  </div>
</div>

And this is with the row - notice how the "Name" label now touches the left side of the input:

<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet"/>

<div class="container">
  <div class="row">
    <div class="form-floating col-6 mb-3 mt-3 ml-auto">
      <input type="text" class="form-control" id="name">
      <label for="name">Name</label>
    </div>
  </div>
</div>

In this minimal example, row might not be needed, but I'm trying to place the form on the left column while putting other content on the right. How can I get this to work?


Solution

  • The problem lies in the grid styles. See:

    .row {
        /* --bs-gutter-x: 1.5rem; */
        /* bs gutter overwrites the form gutter! */
        --bs-gutter-y: 0;
        display: flex;
        flex-wrap: wrap;
        margin-top: calc(var(--bs-gutter-y) * -1);
        margin-right: calc(var(--bs-gutter-x) * -.5);
        margin-left: calc(var(--bs-gutter-x) * -.5);
    }
    

    Solution that worked on my browser:

    Overwrite the gutters on your containing div element back to their original value.

    <div class="form-floating col-6 mb-3 mt-3 ml-auto gx-1">
      <input type="text" class="form-control" id="name">
      <label for="name">Name</label>
    </div>