CSS: Scale font-size to fit parent block element height

后端 未结 2 1835
暗喜
暗喜 2021-01-24 02:52

Almost every question and answer I have found talks about the viewport size; this isn\'t really my issues.

Take this Pen... https://codepen.io/njt1982/pen/pZjZNM

2条回答
  •  北恋
    北恋 (楼主)
    2021-01-24 03:23

    Here you go:

    https://codepen.io/sphism/pen/LBGmRm

    Flexbox solution, scales with browser, works in both portrait and landscape, fonts scale, nice clean html, no svg's.

    EDIT: added the size-* classes so you can easily change the grid size just by adding the class, eg .grid.size-4 would be a 4x4 grid.

    html:

    A
    B
    C
    D
    E
    F
    G
    H
    A
    B
    C
    D
    E
    F
    G
    H
    A
    B
    C
    D
    E
    F
    G
    H
    A
    B
    C
    D
    E
    F
    G
    H
    A
    B
    C
    D
    E
    F
    G
    H
    A
    B
    C
    D
    E
    F
    G
    H
    A
    B
    C
    D
    E
    F
    G
    H
    A
    B
    C
    D
    E
    F
    G
    H

    scss:

    // 100 would have no space around it
    // $gridSize: 90vw; // Works in portrait.
    // $gridSize: 90vh; // Works in Landscape.
    $gridSize: 90vMin; // Works in both.
    
    .container {
      // Full size of page
      height: 100vh;
      width: 100vw;
      // Center the grid x and y
      display: flex;
      align-items: center;
      justify-content: center;
    }
    
    .grid {
      // Grid will center in container if you want a bit of space around it.
      height: $gridSize;
      width: $gridSize;
    
      // This is how we make the grid
      display: flex;
      flex: 0 0 auto;
      flex-wrap: wrap;
    }
    
    // Styles for all tiles
    .tile {
      display: block;
      border: 1px solid gray;
      text-align: center;
      box-sizing: border-box;
    }
    
    // Number of rows and columns.
    // $size: 8;
    @for $size from 1 through 8 {
    
      // eg 100/8 
      $tileSize: $gridSize / $size;
      // Half th esize of the tile, or whatever you want.
      $fontSize: $tileSize * 0.5;
    
      .size-#{$size} {
        .tile {
          // Constrain the tiles to exact size we want.
          width: $tileSize;
          min-width: $tileSize;
          max-width: $tileSize;
          height: $tileSize;
          min-height: $tileSize;
          max-height: $tileSize;
          flex-basis: $tileSize;
    
          // Set fonts to same line height as tile, center them and set font size.
          line-height: $tileSize;
    
          font-size: $fontSize;
        }
    
    
        // Just hide extra divs so it renders properly.
        $maxTiles: $size * $size + 1;
        .tile:nth-child(n + #{$maxTiles}) {
          display: none !important;
        }
      }
    }
    

提交回复
热议问题