微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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.

原文地址:https://www.jb51.cc/html/232044.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐