Search code examples
django-formsdjango-crispy-forms

django crispy forms and bootstrap5 floating labels


I could use some help. I'm trying to use floating labels in a form. It works fine if I hand-code the html. But when I move it to crispy, I lose the floating behavior of the label and the label moves above the input field. Here's a snippet of the crispy code:

Div(
    Div(
        Field('first_name',
              css_class='form-control'),
        css_class='form-floating'),
    css_class="col-md",                
),

and here's the resulting html:

<div class="col-md" > 
  <div class="form-floating" > 
    <div id="div_id_first_name" class="mb-3"> 
      <label for="id_first_name" class="form-label requiredField">
         First name<span class="asteriskField">*</span> 
      </label> 
      <input type="text" name="first_name" maxlength="50" class="form-control textinput textInput" required id="id_first_name">
    </div> 
</div>

Through experimentation, I've figured out the problem is with <div id="div_id_first_name" class="mb-3"> . If this div is eliminated, the floating behavior returns.

My question: what's the best way to solve this? Thanks!


Solution

  • The crispy-bootstrap5 template pack comes with a new layout object for floating fields. You can use this in place of divs with the bootstrap foating class.

    from crispy_bootstrap5.bootstrap5 import FloatingField
    
    # then in your Layout
    ... Layout(
        FloatingField("first_name"),
    )
    
    

    https://github.com/django-crispy-forms/crispy-bootstrap5#whats-new