Search code examples
angularlabelcss-floatprimengangular13

PrimeNG - How to position a label above the input text field


I'm using Angular 13 and PrimeNG 13.4.1. I would like to have a label to be directly above a text field, so I built:

<div class="ui-fluid" style="padding-top: 200px; padding-bottom: 200px;">
  <div class="p-field">
    <span class="p-float-label">
      <input type="text" formControlName="name" pInputText> 
      <label for="formLogoId">My Name</label>
    </span>
  </div>
</div>

However, when the field is rendered, the label appears superimposed over the text input.

enter image description here

What's the proper way to position the label above the text field? I have this in my angular.json file, for what it's worth.

"styles": [
  "node_modules/primeng/resources/themes/nova/theme.css",
  "node_modules/primeng/resources/primeng.min.css",
  "node_modules/primeicons/primeicons.css"
],

Solution

  • Based on the attached HTML, you are applying Float Label.

    If you want the label to be positioned at the top of input field, you can refer to InputText Demo (the Invalid section part).

    HTML

    <div class="p-field">
        <label for="formLogoId">My Name</label>
        <input type="text" formControlName="name" pInputText />
    </div>
    

    CSS

    .p-field > * {
      display: block;
    }
    

    The CSS part is crucial, which all the elements under the element with the p-field class will be applied with style: display: block.

    Without it, the <label> element will be at the left and the <input> element at the right (position).

    Sample StackBlitz Demo

    Output

    enter image description here


    You may consider for PrimeFlex, which is a CSS library for Prime UI.

    1. Install primeflex library.
    npm install primeflex
    
    1. Import CSS in angular.json or root stylesheet.
    "node_modules/primeflex/primeflex.css"
    
    1. Apply PrimeFlex styling.
    <div class="field">
        <label for="formLogoId">My Name</label>
        <input type="text" formControlName="name" pInputText class="w-full" />
    </div>
    

    Refer: FormLayout

    Sample StackBlitz Demo (PrimeFlex)