html - 我的网站在 Firefox 和 Chrome 中看起来不同

标签 html css google-chrome firefox

我一直在 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;
}

我怎样才能使它们相同?

最佳答案

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

在 Chrome 中:

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

在 Firefox 中:

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

CSS 布局中的值通常从 double 转换为 float 然后返回,或者四舍五入到小数点后几位。这种布局很脆弱,因为它取决于 5*width(ship) ≤ width(shipBoard)。浮子被设计成在必要时包裹起来。无论缩放级别如何,CSS 中的某些长度(尤其是边框)偶尔会捕捉到整数像素。

Flexbox 或网格将是替代 float 的不错选择,但在您的 CSS 中将宽度属性更改为 151px755px 可以解决此问题。

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

关于html - 我的网站在 Firefox 和 Chrome 中看起来不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54466474/

相关文章:

css - 使用 scss @each 生成 css 变量不起作用

html - 如果 div 有边框,则不需要 1px 填充。仅在 Chrome

html - 在不移动元素的情况下计算出网格元素

mysql - 通过 mysql 输出更改 div 位置基础

css - 为什么有些网页在移动设备上显示在平板电脑 View 中?

firefox - 在 Firefox 和 chrome 中设置自定义 cookie?

google-chrome - 谷歌浏览器位置 :fixed border-radius overflow:hidden issue

html - 如何让我的按钮响应?

html - 下载 CSV 生成的客户端

css - 如何使照片填充列大小(Bootstrap)?