首页 > 解决方案 > 我的网站在 Firefox 和 Chrome 中看起来不同

问题描述

我一直在 Chrome 上的网页上工作,并意识到它在 Firefox 中看起来不一样。我已经简化了代码以显示问题。似乎最后一个没有显示在 Firefox 中,而它在 Chrome 中可见。

这是我的html文件。

<!DOCTYPE html>
<html>

  <meta charset="utf-8">

  <link rel="stylesheet" type="text/css" href="style.css">



  <div id=shipBoard align="right" style="overflow: hidden">

    <div id="ship" style="float: left;">
      <img src="carrier.jpg" style="width:100px;height:100px;">
    </div>

    <div id="ship" style="float: left;">
      <img src="destroyer.jpg" style="width:100px;height:100px;">
    </div>

    <div id="ship" style="float: left;">
      <img src="test.jpg" style="width:100px;height:100px;">
    </div>

    <div id="ship" style="float: left;">
      <img src="battleship.jpg" style="width:100px;height:100px;">
    </div>

    <div id="ship" style="float: left;">
      <img src="sub.jpg" style="width:100px;height:100px;">
    </div>

  </div>

</html>

这是css文件:

#ship {
  position: relative;
  width: 4cm;
  height: 5cm;
  margin-left: auto;
  margin-right: auto;
  background-color: white;
}

#shipBoard {
  position: relative;
  width: 20cm;
  height: 5cm;
  margin-left: auto;
  margin-right: auto;
  background-color: green;
}

我该怎么做才能使它们相同?

标签: htmlcssgoogle-chromefirefox

解决方案


亚像素定位很棘手。该cm单位不映射到整数个像素(它被定义为1cm = 96px/2.54)。

在 Chrome 中:

> getComputedStyle(document.querySelector('#shipBoard')).width
"755.891px"
> getComputedStyle(document.querySelector('#ship')).width
"151.172px"

在火狐中:

> getComputedStyle(document.querySelector('#shipBoard')).width
"755.9px"
> getComputedStyle(document.querySelector('#ship')).width
"151.183px"

CSS 布局中的值通常从双精度数转换为浮点数并返回,或者四舍五入到小数点后几位。这种布局很脆弱,因为它取决于 5*width(ship) ≤ width(shipBoard)。浮动设计为在必要时进行包装。CSS 中的某些长度,尤其是边框,有时会捕捉到整数个像素,而不管缩放级别如何。

Flexbox 或网格将是一个不错的选择,而不是浮动,但是将宽度属性更改为CSS151px755px在您的 CSS 中可以解决此问题。

另外,不要id=在多个元素上使用相同的,这是无效的。


推荐阅读