csstailwind-css

How to align absolute elements


I have an input field that looks like this

    <div className="relative">
      <input
        className="peer border h-12 w-52 focus:pt-6 focus:outline-none"
        type="text"
      />
      <label className="absolute left-0 top-1/2 -translate-y-1/2 transition-all peer-focus:top-1/4">
        Name
      </label>
    </div>

I did not set padding for either the input and the label, but they are not aligned.

enter image description here

What could be the cause of this and how can I fix it.


Solution

  • The cause is from the <input> element having a border while the <label> does not. This makes the <input> horizontally offset by 1px, the width of the border.

    You could consider:

    <script src="https://cdn.tailwindcss.com/3.4.16"></script>
    
    <div class="relative">
      <input
        class="peer border h-12 w-52 focus:pt-6 focus:outline-none"
        type="text"
        value="Name"
      />
      <label class="absolute left-0 top-1/2 -translate-y-1/2 transition-all peer-focus:top-1/4 left-px">
        Name
      </label>
    </div>

    <script src="https://cdn.tailwindcss.com/3.4.16"></script>
    
    <div class="relative">
      <input
        class="peer border h-12 w-52 focus:pt-6 focus:outline-none"
        type="text"
        value="Name"
      />
      <label class="absolute left-0 top-1/2 -translate-y-1/2 transition-all peer-focus:top-1/4 mx-px">
        Name
      </label>
    </div>

    <script src="https://cdn.tailwindcss.com/3.4.16"></script>
    
    <div class="relative">
      <input
        class="peer border h-12 w-52 focus:pt-6 focus:outline-none"
        type="text"
        value="Name"
      />
      <label class="absolute left-0 top-1/2 -translate-y-1/2 transition-all peer-focus:top-1/4 border border-transparent">
        Name
      </label>
    </div>

    <script src="https://cdn.tailwindcss.com/3.4.16"></script>
    
    <div class="relative">
      <input
        class="peer outline outline-1 outline-[theme(borderColor.DEFAULT)] h-12 w-52 focus:pt-6"
        type="text"
        value="Name"
      />
      <label class="absolute left-0 top-1/2 -translate-y-1/2 transition-all peer-focus:top-1/4">
        Name
      </label>
    </div>

    <script src="https://cdn.tailwindcss.com/3.4.16"></script>
    
    <div class="relative">
      <input
        class="peer ring ring-1 ring-[theme(borderColor.DEFAULT)] h-12 w-52 focus:pt-6 focus:outline-none"
        type="text"
        value="Name"
      />
      <label class="absolute left-0 top-1/2 -translate-y-1/2 transition-all peer-focus:top-1/4">
        Name
      </label>
    </div>