Search code examples
cssmaterialize

Materializecss: Is there any class to make a text prefix to a text-input


I need something to prefix my input text in MaterializeCss. Although it provides 'prefix' class to serve that purpose, it doesn't work properly when I need to add multiple words as a span. For your information, I need something equivalent to Bootstrap input-group-addon class.

Code:

<div class="container">
      <div class="input-field">
        <span class="prefix">Full Name</span>
        <input type="text" name="" id="" />
      </div>
   <br> 
   <br> 
    <div class="input-field">
        <i class="prefix material-icons">attach_money</i>
        <input type="text" name="" id="" />
      </div>
   </div>

this picture shows when I use a single icon it works fine but breaks down in case for multiple words

I highly appreciate your wise replies.


Solution

  • I think you've misunderstood what the materializecss prefix is. As it states in the docs, it is called Icon Prefix - out of the box they provide the ability to prefix with an icon:

    Icon Prefixes You can add an icon prefix to make the form input label even more clear. Just add an icon with the class prefix before the input and label.

    <div class="input-field col s6">
      <i class="material-icons prefix">mode_edit</i>
      <textarea id="icon_prefix2" class="materialize-textarea"></textarea>
      <label for="icon_prefix2">First Name</label>
    </div>
    

    enter image description here

    The span class of .prefix that you're trying to add doesn't exist in materialize - it is for the icon tag.

    "Full name", the way you are trying to use it, as a clue to what the input is - would be a label element. A prefix allows you to provide information that adds to the input (such as a dollar sign) or a shorthand, for instance an email symbol.

    You could custom code the same feature from bootstrap, but it is a very different element altogether - and you need to rephrase the question as saying the prefix isn't working correctly is not accurate.

    https://materializecss.com/text-inputs.html

    EDIT:

    If we dive into the css for the default, rather than using flex in Bootstrap, materializecss uses absolute positioning, because it is meant for icons that have standard consistent width:

    .input-field .prefix {
        position: absolute;
        width: 3rem;
        font-size: 2rem;
        -webkit-transition: color .2s;
        transition: color .2s;
        top: .5rem;
    }
    
    input-field .prefix ~ input {
        margin-left: 3rem;
        width: 92%;
        width: calc(100% - 3rem);
    }
    

    The icon is given 3rem width, and then the input is given 3rem margin-left to accommodate it. I've adjusted these values up to 10rem to make it work for your text input - but if the text was any longer or shorter, you'd need to manually update this new rem value:

    https://codepen.io/doughballs/pen/XWbgWKg