How to calculate the amount of flexbox items in a row?

后端 未结 11 1858
北荒
北荒 2020-12-04 12:12

A grid is implemented using the CSS flexbox. Example:

The number of rows in this example is 4 because I fixed the container width for demo purposes. But, in

11条回答
  •  抹茶落季
    2020-12-04 12:29

    I know this is not exactly what OP is asking for, but I wanted to show a possible alternative (depends on use-case).

    Instead of using CSS flexbox, there is also the more recent CSS grid which actually features columns and rows. Thus by converting the structure to a grid and using some JS to listen to the key buttons being pressed, the active item can be moved (see incomplete working example below).

    var x = 1, y = 1;
    document.addEventListener('keydown', function(event) {
        const key = event.key; 
        // "ArrowRight", "ArrowLeft", "ArrowUp", or "ArrowDown"
        console.log(key);
        
        if (key == "ArrowRight") {
          x++;
        }
        if (key == "ArrowLeft") {
          x--;
          if (x < 1) {
            x = 1;
          }
        }
        if (key == "ArrowUp") {
          y--;
          if (y < 1) {
            y = 1;
          }
        }
        if (key == "ArrowDown") {
          y++;
        }
        document.querySelector('.active').style.gridColumnStart = x;
        document.querySelector('.active').style.gridRowStart = y;
    });
    .grid {
      display: grid;
      grid-template-columns: repeat(auto-fill,50px);
      grid-template-rows: auto;
      grid-gap: 10px;
      width: 250px;
      height: 200px;
      background-color: #ffffd;
      padding: 10px;
    }
    
    .item {
      width: 50px;
      height: 50px;
      background-color: red;
      margin: 0 10px 10px 0;
      display: flex;
      justify-content: center;
      align-items: center;
    }
    
    .active {
      outline: 5px solid black;
      grid-column-start: 1;
      grid-column-end: span 1;
      grid-row-start: 1;
      grid-row-end: span 1;
    }
    A1
    A2
    A3
    A4
    B1
    B2
    B3
    B4
    C1
    C2

    However, as stated above, this solution has flaws. For once, the active item is actually a grid item by itself and moved along the grid with the other elements flowing around it. Secondly, similar to flexbox model, there are currently no CSS selectors to target an item based upon its grid position.

    However, since we are using javascript anyway, you could loop through all grid items and get the CSS Grid properties. If they match the current coordinates, you have your target element. Sadly, this would only work if each element is placed, using grid-column-start: auto for elements doesn't help. Even window.getComputedStyle() will only return auto;

提交回复
热议问题