首页 > 解决方案 > 如何在div顶部对齐输入中的文本

问题描述

当将一个 div 放在另一个 div 后面时,bot div 元素中的文本是对齐的。

.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>

当带有类的 divtop被替换为输入时,文本偏移 1px,尽管边框仍然正确对齐。

.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>

我无法置身事外。有人在这里解释它并建议如何解决这个问题?

标签: htmlcssz-index

解决方案


发生这种情况是因为如何处理输入。输入元素内的文本字段被拉伸以适应框大小。在本例中为 34 像素。所以解决方法是增加 div 的 line-height 以匹配输入的 34px。

.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>


推荐阅读