html – 浏览器的1px计算问题(子像素问题)

我认为这个问题很常见,并且在SO本身就已经找到了,但是找不到如何解决这个问题.

问题:

当您调整窗口大小时,您会注意到两个图像的高度有时会相差1px(当浏览器调整尺寸时,这是预期的).

如何“修复”此UI问题?我知道我可以通过使用flexBox来做到这一点.但我想有一个更好的解决方案.你们可以跳进去吗?

table{
  width:100%;
  border-collapse: collapse;
}
img{
  display: block;
  width: 100%;
}
<table>
  <tr>
    <td><img src="http://placehold.it/100x100"/></td>
    <td><img src="http://placehold.it/100x100"/></td>
  </tr>
</table>

甚至在这里我使用display:table:

.wrapper{
  width:100%;
  display: table;
}
.wrapper div{
  display: table-cell;  
}
img{
  display: block;
  width: 100%;
}
<div class="wrapper">
    <div><img src="http://placehold.it/100x100"/></div>
    <div><img src="http://placehold.it/100x100"/></div>
</div>

编辑:
Firefox浏览器中没有此问题,但Chrome中存在此问题.

请注意,当我使用flexBox时,问题不存在:

body{
  margin: 0;  
}
.wrapper{
  width:100%;
  display: flex;
}
.wrapper div{
  flex: 1;  
}
img{
  display: block;
  width: 100%;
}
<div class="wrapper">
    <div><img src="http://placehold.it/100x100"/></div>
    <div><img src="http://placehold.it/100x100"/></div>
</div>

或使用浮点数和内联块:

body{
  margin: 0;  
}
.wrapper{
  width:100%;
  display: block;
}
.wrapper div{
  display: inline-block;
  float: left;
  width:50%;
}
.wrapper:after{
  content: '';
  display: inline-block;
  clear:both;
}
img{
  display: block;
  width: 100%;
}
<div class="wrapper">
    <div><img src="http://placehold.it/100x100"/></div>
    <div><img src="http://placehold.it/100x100"/></div>
</div>

解决方法

那是因为 Sub-Pixel Problems.

每张图片占据容器的50%.例如,如果容器宽度为100px,则每个图像的宽度为50px.

但是容器的宽度可以是奇数个像素,例如,101px.那么有三种合理的可能性:

>将一个图像宽50px,另一个51px.然后,即使您为这两个图像指定了相同的宽度,图像也不会同样宽.
>使两幅图像都宽50px.然后将有1px的差距
>使两幅图像都宽51px.然后它们将不适合,溢出容器或包裹到下一行.

每个选择都有其缺点,但现在浏览器似乎更喜欢第一个选项.然而,在这种情况下,图像具有固有的纵横比,因此不同的宽度将产生不同的高度,然后1px间隙是水平而不是垂直创建的.

似乎Firefox检测到,因此使较小的图像与另一个一样高,打破了宽高比. Chrome更喜欢强制使用宽高比.

没有办法改变这一点.它完全依赖于实现:

The especially strange part,in all of this,is that there’s really no right,or wrong,here. How this behavior is supposed to play out by the rendering engine isn’t dictated by the CSS specification,having it be left up to the implementation to render as it sees fit.

相关文章

vue阻止冒泡事件 阻止点击事件的执行 &lt;div @click=&a...
尝试过使用网友说的API接口获取 找到的都是失效了 暂时就使用...
后台我拿的数据是这样的格式: [ {id:1 , parentId: 0, name:...
JAVA下载文件防重复点击,防止多次下载请求,Cookie方式快速简...
Mip是什么意思以及作用有哪些