无法计算的像素,它们来自哪里?

时间:2017-10-14 17:47:38

标签: html css

给出以下代码:

["Rock", "Paper", "Scissors"].sample
.wrapper {
  margin: 0;
  padding: 5px 2px;
}

.box {
  width: 100px;
  outline: 0;
  padding: 0;
  margin: 0;
  font-size: 12px;
  border: 1px solid black;
}

.box2 {
  resize: none;
}

code in codepen

我希望两个<div class="wrapper"> <input class="box box1" value="input text here" /> </div> <div class="wrapper"> <textarea class="box box2" rows="1">input text here</textarea> </div>元素的高度相同,但事实并非如此。

两个wrapper元素的高度相同:box 17px包装器的高度为:box1 28px包装器的高度为:box2

两个问题:

  1. 为什么31px包装的高度是28而不是27?
  2. 为什么两个包装纸的高度不一样?我如何使它们相同?

3 个答案:

答案 0 :(得分:2)

差距的原因是textareainline都是inline-block(或textarea)元素。但是,display: block的差距在不同的浏览器中有所不同。

要解决此问题,请将.box添加到vertical-align: top(两个元素)或将textarea添加到var $canvas $(function(){ $canvas=$("div.canvas") setInterval(scroll, 5000); }); function scroll(){ if ($canvas.position().left!=-1195){ $canvas.animate({left: "-=239"}); }else{ $canvas.animate({left: 0}); } }

答案 1 :(得分:2)

wrapper - 元素的大小不同的原因是textarea和input元素自然是inline-blockinline元素(取决于浏览器)。差距是由一些浏览器引起的,因为它们为下一步的内容预留了空间。奇怪的是,这不适用于void - input等元素。

要解决此问题,您可以将vertical-align: top应用于textareadisplay: block两个元素。

.wrapper {
  margin: 0;
  padding: 5px 2px;
}

.box {
  width: 100px;
  outline: 0;
  padding: 0;
  margin: 0;
  font-size: 12px;
  border: 1px solid black;
}

.box2 {
  resize: none;
}

.fix1 {
  vertical-align: top;
}

.fix2 {
  display: block;
}
<div class="wrapper">
  <input class="box box1" value="input text here" />
</div>
<div class="wrapper">
  <textarea class="box box2 fix1" rows="1">input text here</textarea>
</div>

<div class="wrapper">
  <input class="box box1 fix2" value="input text here" />
</div>
<div class="wrapper">
  <textarea class="box box2 fix2" rows="1">input text here</textarea>
</div>

答案 2 :(得分:0)

box1box2的大小不同,原因是因为它们适应内容高度,两种输入类型的默认字体都不同,导致高度略有不同 - 即使您将它们设置为相同的字体大小,字体的垂直间距也会略有不同。

注意:您还需要将wrapper类的行高设置为相同的值(我在下面的示例中使用了1em)。

检查您的示例与应用这两项更改之间的差异:

.wrapper {
  margin: 0;
  padding: 5px 2px;
}

.box {
  width: 100px;
  outline: 0;
  padding: 0;
  margin: 0;
  font-size: 12px;
  border: 1px solid black;
}

.box2 {
  resize: none;
}

.testwrapper {line-height:1em;}
.testbox { font-family: 'sans serif';}
<p>Your example:</p>
<div class="wrapper">
  <input class="box box1" value="input text here" />
</div>
<div class="wrapper">
  <textarea class="box box2" rows="1">input text here</textarea>
</div>

<p>With the same font and line-height:</p>
<div class="wrapper testwrapper">
  <input class="box box1 testbox" value="input text here" />
</div>
<div class="wrapper testwrapper">
  <textarea class="box box2 testbox" rows="1">input text here</textarea>
</div>

相关问题