我一直在 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 中将宽度属性更改为 151px
和 755px
可以解决此问题。
此外,不要在多个元素上使用相同的 id=
,这是无效的。
关于html - 我的网站在 Firefox 和 Chrome 中看起来不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54466474/