Home > front end >  Aligning an icon to the right inside label tag
Aligning an icon to the right inside label tag

Time:05-23

I tried changing the style of the i tag to 'float:right' in order to align the icon to the right, but it didn't work. The ideal look would be like the image below. Thanks in advance.

enter image description here

<div >
<div >
    <label for="form-realname" >TEXT<i  aria-hidden="true" style="float:right;"></i></label>
    <div>
        <input type="text"  id="form-test" name="test" autocomplete="off">
    </div>
</div>

CodePudding user response:

You need to use flex justify-content with space-between. Also, please do not use float to align items in new code, this should be considered legacy.

It looks like you are using Bootstrap so you can simply add the justify-content-between class to your label.

More info here: https://getbootstrap.com/docs/4.0/utilities/flex/#justify-content

<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.1.1/css/all.min.css" rel="stylesheet"/>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet"/>

<div >
    <div >
        <label for="form-test" >TEXT
            <i  aria-hidden="true"></i>
        </label>
        <div>
            <input type="text"  id="form-test" name="test" autocomplete="off">
        </div>
    </div>
</div>

Also, note that the for attribute should point to the id of the input it is describing (in this case form-test).

CodePudding user response:

Here is my simplified solution for your problem. You can paste it on some js and html playground (codesandbox, jsfiddle, etc.) to understand the idea

You can base on it to do what you need.

<body>
  <style>
    .flex-container {
      display: flex;
      justify-content: space-between;
      width: 200px;
    }
    .input-div {
      width: 200px;
    }
  </style>
  
  <div >
    <div >
      <div >
        <label>TEXT1</label>
        <label>TEXT2</label> // Your <i> tag goes here
      </div>
      <div>
        <input  type="text"  id="form-test" name="test" autocomplete="off">
      </div>
    </div>
</body>

The idea is:

  • You need to set the input width and the container of the label and icon the same. (With bootstrap, you can use class col for them)
  • The label and icon are not nested as you did, separate it out like I did
  • Styling the label and icon container with flex, and justify-content: space-between
  • Related