Viscous positioning

  • Scroll to the container

    (Overflow: auto) If an element has sticky attributes, it will stick to the nearest ancestor element that has a scrolling mechanism (overflow: auto)

  • Effect of rendering

    In a rolling container

    When an element crosses a certain threshold, the effect shown is consistent with relative

    When an element crosses a certain threshold, it appears as fixed

  • Matters needing attention

    The parent element cannot set overflow: Hidden or overflow: Auto

    Sticky positioning must be specified for one of the four thresholds, top, right, bottom or left, otherwise it behaves the same as relative positioning

  • Scenario 1 – The top suction is fixed

    .sticky {
      position: sticky;
      top: 0;
    }  
    Copy the code
  • Scenario 2 – Fix the table header

    .sticky th {
      position: sticky;
      top: 0; z-index: 20;
      background-color: #E6EDFF;
      border: 1px solid #ebeef5;
    }
    Copy the code
  • Scenario 3 – Fix the first column

    .sticky th:first-child,
    .sticky td:first-child {
      position: sticky;
      left: 0; z-index: 20;
    }
    Copy the code

A table with fixed headers and columns

  • Setting up the scroll container

    <div class="container"></div>
    Copy the code
    .container {
      overflow: auto;
    }
    Copy the code

    Note: You need to specify the height or maximum height of the rolling container to achieve the desired effect

  • Table initialization

    table {
      width: 100%;
      table-layout: fixed;
      border-collapse: collapse;
      border-spacing: 0;
    }
    Copy the code

    In a fixed layout, the width of each column is determined by the first row, and subsequent widths are ignored

    Reduce redrawing during table rendering to improve performance

  • The left and right borders that hold rows and columns in place disappear when scrolling

    th.td{&::before, &::after {
        content: ' ';
        position: absolute
      }
      &::before {
        left: 0; bottom: 0;
        width: 100%; height: 1px;
        background-color: #ebeef5;
      }
      &::after {
        left: 0; top: 0;
        height: 100%; width: 1px;
        background-color: #ebeef5; }}td {
      position: relative;
    }
    .container {
      border-top: 1px solid #ebeef5;
      border-right: 1px solid #ebeef5;
    }
    Copy the code

    Use pseudo-elements to simulate the left and bottom borders, and add a right and top border to the outermost container

  • When scrolling, the crossing cell in the upper left corner is overwritten by scrolling elements on the right and below

    The level Z-index is greater than the level of the fixed element

  • Text overflow displays ellipsis

    .ellipsis {
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }
    Copy the code

    In order for text-overflow: ellipsis to work, you need to specify the width for the header of the target column