Search code examples
htmlcssalignmentvertical-alignment

Vertical center an absolutely positioned input field inside its surrounding element


I simply want to vertically center an input field inside its surrounding DIV, but at the same time all input fields on the page should be horizontally aligned with each other (should have the same left value, if you will).

Here's an example page of the problem:

.wrapper {
  border: 1px solid #000;
  border-radius: 10px;
  margin: 10px;
  padding: 10px;
  line-height: 40px;
}
.inputClass {
  position: absolute;
  left: 25%;
  /* top: 50%; transform: translate(0, -50%); */
  /* not working as I need */
  vertical-align: middle;
}
<div class="wrapper">
  <div>
    <div>
      Some text
      <input type="text" class="inputClass" />
    </div>
    <div>
      Some more text
      <input type="text" class="inputClass" />
    </div>
  </div>
</div>

Desired result (blue rim by Firebug): enter image description here


Solution

  • You can group inputs+labels in fieldsets and then use the labels for moving the inputs towards the center,

    try this:

    .wrapper {
      border: 1px solid #000;
      border-radius: 10px;
      margin: 10px;
      padding: 10px;
      line-height: 40px;
    }
    
    fieldset {
      border: 0;
      /*resets UA*/
    }
     /*can use label to move inputs right*/
    label {
     width:40%;
     display:inline-block;
     padding-right :15px;
     text-align:right
     }
    <div class="wrapper">
      <div>
        <fieldset>
          <label for='one'>Some text</label>
          <input id='one' type="text" class="inputClass" />
        </fieldset>
        <fieldset>
          <label for='two'>Some more text</label>
          <input id='two' type="text" class="inputClass" />
        </fieldset>
      </div>
    </div>