Place square svg to the center of the screen, scale it to fit the screen's width and height with some constraints

后端 未结 6 1419
臣服心动
臣服心动 2021-02-14 14:03

It seem to be a silly question and possibly a dupe, but I couldn\'t find a good solution for a while, so finally dare to ask.

I want to place an

6条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-02-14 14:48

    The following works if the aspect ratio of the SVG is a given. If the aspect ratio of the SVG is dynamic, you have to use JavaScript, I believe.

    This snippet works in modern browsers and takes full advantage of the relatively new vmin viewport-percentage length. Browser support is pretty good. For horizontal and vertical centering, the flexbox layout mode is leveraged. Again, browser support is pretty good.

    The trick is that the dimensions of the SVG are set relative to either the width or the height of the screen, whichever is smallest. This means that even when we would set it to be 100vmin, the SVG is guaranteed to fit the screen (but barely). To enforce maximal dimensions, good old max-width and max-height are used, exactly as they are intended to be used.

    html, body {
      /* ensure that all of the viewport is used */
      width: 100%;
      height: 100%;
      /* ensure that no scrollbars appear */
      margin: 0;
      padding: 0;
      
      /* center SVG horizontally and vertically */
      display: flex;
      align-items: center;
      justify-content: center;
    }
    
    #picture {
      /* ensure 1:1 aspect ratio, tweak 50 to make SVG larger */
      width: 50vmin;
      height: 50vmin;  
      /* set some maximum size (width and height need to match
       * aspect ratio, 1:1 in this case */
      max-width: 200px;
      max-height: 200px;
    }
    
      
    

提交回复
热议问题