首页 > 解决方案 > 无效的 CSS left 属性是否可以接受?

问题描述

我发现了一些奇怪的行为,至少对我来说是这样。如果有人向我解释这一点,我将不胜感激。

此代码仅在 Firefox 中按预期工作,在 Chrome 或 Opera 中,红色块距离所需位置 1px。

* {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}

body {
  padding: 40px;
  height: 100vh;
}
.content {
  border: 1px solid black;
  height: 100px
}
.bottom {
  position: absolute;
  top: 20px;
  left: 50%;
  transform: translateX(-50%);

  height: 40px;
  width: calc(100% - 80px);
  
  border: 1px solid red;
}
<div class="content"></div>
<div class="bottom"></div>

如果我只是将左属性更改为某个无效值left: invalid并删除转换,它在我测试的其他浏览器中工作正常。

* {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}

body {
  padding: 40px;
  height: 100vh;
}
.content {
  border: 1px solid black;
  height: 100px
}
.bottom {
  position: absolute;
  top: 20px;
  left: invalid;

  height: 40px;
  width: calc(100% - 80px);
  
  border: 1px solid red;
}
<div class="content"></div>
<div class="bottom"></div>


我的配置

系统:Ubuntu 18.04.5 LTS

浏览器

我还注意到,这只发生在宽度均匀的情况下。

标签: htmlcss

解决方案


没有视觉差异的原因是该left: 50%属性将元素了其父元素的 50%,而该transform: translateX(-50%)属性将元素推回了 50%,即在 X 方向上将元素向前推了 -50%,其自身宽度.

在第二个代码片段中,由于该值invalid确实是invalid,浏览器忽略了它。此外,由于没有翻译,它也不会推动。因此,UI 没有区别。


推荐阅读