是否可以对 css 中的值进行舍入?或者,如何解决 half/sub-pixels on % translated layouts?

Is it possible to round values in css? Or, how to solve half/sub-pixels on % translated layouts?

我有个奇怪的问题。我构建了一个 flex/grid 全屏响应式界面。我使用了 % 值。它工作正常,但有时,通过调整 window 的大小,项目(水平、垂直或两者)之间会出现一条 1 px 的直线。我想这可能是因为,使用 % 值并作为液体元素,项目大小并不总是完美的像素。看:

如何避免这种情况,同时保持响应式布局?

我通过非常小的缩放内部元素(图像和翻转层)(如 scale(1.005))设法取得了一些不错的效果,但它并不总是完美的。问题是浏览器不能在全屏布局上舍入元素大小,或者类似的东西,不知道。

只是对我的原始代码进行了一些抽象,只是为了添加上下文。这是一个 3 列的 flex 布局,其中 1 列是 50% 宽度(第三个在屏幕外 > 整体表现像 3 个面板 'slideshow')。第二列,本身包含图片上的网格:

/* HTML */

<div class="sections-list">
  <div class="section column-1"></div>

  <div class="section column-2">
    <div class="grid">
      <button type="button">a</button>
      <button type="button">b</button>
      <button type="button">c</button>
      <button type="button">d</button>
    </div>  
  </div>

  <div class="section column-3"></div>
</div>


/* SCSS */

.sections-list{
  display: flex;
  justify-content: flex-start;
  min-height: 100vh;

  translateX(-50%);
}

.section{
  flex-grow:1;
  min-width: 50%;
  box-sizing:border-box;
  min-height: 100vh;
}

.grid{
  display: grid;
  height: 100%;
  grid-template:
    "a   b" 50%
    "c   d" 50%
    / 50% 50%;

  button{
    display: block;
    position: relative;
    overflow: hidden;
    padding: 0;
    min-width: none;
    max-width: none;
    height: auto;

    &:nth-child(1){ grid-area: a; }
    &:nth-child(2){ grid-area: b; }
    &:nth-child(3){ grid-area: c; }
    &:nth-child(4){ grid-area: d; }
  }
}

原来是主元素翻译了50%导致的问题。当 window.width 为奇数时,这会导致半个像素。

我的解决方案是使用一些 javascript、css --properties 和遗留浏览器的回退重新计算和舍入翻译。这是一些简化的代码(也请查看原始代码):

:root{
  --half-window: -50%;
}

.sections-list{
  display: flex;
  justify-content: flex-start;
  min-height: 100vh;

  transform: translatex(-50%); // legacy
  transform: translatex(var(--half-window));
}

然后:

function round_half_window(){
  document.documentElement.style.setProperty('--half-window', -Math.round($(window).width()/2) + 'px');
}

$window.resize(_.debounce(function(){ round_half_window(); },500));
round_half_window();