Search code examples
htmlcssz-index

How to align text in input on top of div


When putting a div behind another div the text in bot div elements is aligned.

.wrapper {
  box-sizing: border-box;
  padding: 0;
  margin: 0;
  outline: none;
  padding-right: 20px;
}

.box {
  height: 34px;
  width: 130px;
  padding: 6px 12px;
  font-size: 24px;
  font-family: Verdana;
  color: #555555;
  background: rgba(255, 255, 255, 0) none;
  border: 1px solid #cccccc;
  border-radius: 4px;
}

.top {
  z-index: 2;
  position: relative;
}

.underlayer {
  top: -48px;
  z-index: 1;
  position: relative;
    background: rgba(255, 255, 255, 1);
      color: #c8c8c8;
      margin:0;
}
<div class="wrapper">
  <div type="text" class="box top">20-123</div>
  <div class="box underlayer">20-123-20</div>
</div>

When the div with class top is replaced with an input, the text is 1px off, though the border is still aligned correctly.

.wrapper {
  box-sizing: border-box;
  padding: 0;
  margin: 0;
  outline: none;
  padding-right: 20px;
}

.box {
  height: 34px;
  width: 130px;
  padding: 6px 12px;
  font-family: Verdana;
  font-size: 24px;
  color: #555555;
  background: rgba(255, 255, 255, 0) none;
  border: 1px solid #cccccc;
  border-radius: 4px;
}

.top {
  z-index: 2;
  position: relative;
}

.underlayer {
  top: -48px;
  z-index: 1;
  position: relative;
    background: rgba(255, 255, 255, 1);
      color: #c8c8c8;
      margin:0;
}
<div class="wrapper">
  <input type="text" value="20-123" class="box top">
  <div class="box underlayer">20-123-20</div>
</div>

I can't put my head around it. Somebody here to explain it and suggest how to resolve this ?


Solution

  • This happens because of how inputs are handled. The textfield inside an input-element is streched to fit the box size. In this case 34px. So the fix is to increase the div's line-height to match the 34px of the input.

    .wrapper {
      box-sizing: border-box;
      padding: 0;
      margin: 0;
      outline: none;
      padding-right: 20px;
    }
    
    .box {
      height: 34px;
      width: 130px;
      padding: 6px 12px;
      font-family: Verdana!important;
      font-size: 24px;
      color: #555555;
      background: rgba(255, 255, 255, 0) none;
      border: 1px solid #cccccc;
      border-radius: 4px;
    }
    
    .top {
      z-index: 2;
      position: relative;
    }
    
    .underlayer {
      top: -48px;
      line-height: 34px;
      z-index: 1;
      position: relative;
        background: rgba(255, 255, 255, 1);
          color: #c8c8c8;
          margin:0;
    }
    <div class="wrapper">
      <input type="text" value="20-123" class="box top">
      <div class="box underlayer">20-123-20</div>
    </div>