Search code examples
cssglyphicons

How Can I Use CSS :after to Add a Glyphicon Element to an Input


I have an <input> element, and I can't modify the HTML around it, but I want to add a glyphicon (<i class="glyphicons glyphicons-some-icon"/>) inside of it. I was hoping to do it with CSS, but I can't seem to get :after to work. I thought something like the following would generate that element:

#my-input {
    content: attr(class, 'glyphicons glyphicon-some-icon'); 
    content: '<i/>'; 
}

but it doesn't. Could anyone who understands :after better explain how I can generate the desired <i class="glyphicons glyphicons-some-icon"/> using :after?


Solution

  • :before and :after are applied inside a container, which means you can use it for elements with an end tag.see explanation

    See below example. to achieve what you want.

    NOTE: parent position is relative so that chilled absolute position will take top and bottom depending on parent.

    .myInput:after {
      font-family: FontAwesome;
      content: "\f0a9";
      position: absolute;
      top: 3px;
      left: 7px;
    }
    .my{
    position:relative
    }
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.4.0/css/font-awesome.css" rel="stylesheet" />
    
    <div class="my">
    
      <div class="myInput">
        <input type="text" />
      </div>
    
    </div>

    OR

    .mystyle:before {
      font-family: FontAwesome;
      content: "\f0a9";
    }
    .myInput {
      position: relative;
    }
    .myInput div {
      position: absolute;
      top: 3px;
      left: 5px;
    }
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.4.0/css/font-awesome.css" rel="stylesheet" />
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div class="myInput">
      <input class="mystyle" type="text" value="" />
      <div class="mystyle"></div>
    </div>