代码之家  ›  专栏  ›  技术社区  ›  Luca Reghellin

是否可以在css中舍入值?或者,如何在%转换的布局上求解半像素/亚像素?

  •  0
  • Luca Reghellin  · 技术社区  · 7 年前

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

    enter image description here

    我怎样才能避免这种情况,仍然保持一个快速响应的布局?

    我通过很小的缩放内部元素(图像和滚动层)来达到一些好的效果,比如 scale(1.005) ,但它并不总是完美的。问题是浏览器不能在全屏布局上舍入元素大小,或者类似的东西,不知道。

    只是对原始代码的一点抽象,只是为了添加上下文。这是一个3 col s flex布局,其中1 col是50%宽度(第三个是屏幕外的>整体行为就像3个面板的“幻灯片放映”)。第二列本身包含图片上的网格:

    /* 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; }
      }
    }
    
    1 回复  |  直到 7 年前
        1
  •  0
  •   Luca Reghellin    7 年前

    所以,原来问题是由主元素的50%翻译引起的。当 window.width 很奇怪。

    对我来说,解决方案是使用一些javascript、css属性和对传统浏览器的回退来重新计算和循环转换。下面是一些简化的代码(请同时查看原始代码):

    :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();
    
    推荐文章