htmlcsssvgfrontendweb-frontend

Appearance of svg object in mobile view is different from desktop view


body {
  margin: 0vh 0vw;
}

.header {
  position: relative;
  width: 100%;
  height: 12vh;
  background-color: #004d40;
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: hidden;
  top: 0;
}

.line {
  position: absolute;
  left: 0;
  top: calc(50%);
  width: 100%;
  height: 0.25vh;
  background-color: white;
  z-index: 1;
}

svg {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, 0%);
  z-index: 2;
}
<!DOCTYPE html>
<html lang="tr">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>SVG Header with Half Circle</title>
</head>

<body>

  <div class="header">
    <div class="line"></div>
    <svg width="10vw" height="5vh" viewBox="0 0 100 50" xmlns="http://www.w3.org/2000/svg">
        <path d="M0,0 A50,50 0 0,0 100,0" fill="#004d40" stroke="white" stroke-width="3"/>
    
    </svg>
  </div>

</body>

</html>

Hello, when the svg object goes to mobile view, the svg gets distorted and a gap occurs between the semicircle and the line. Why is this caused and how can we solve it.

on dekstop:

enter image description here

on mobie emulation:

enter image description here

Expected Result:

I was expecting it to look the same on mobile as on desktop.


Solution

  • By default the SVG is trying to fit and align the lines into the center of the viewBox (or viewport) it is given. You can control this behavior with the preserveAspectRatio attribute on the <svg> element.

    In the example below I've used the value xMidYmin meet which translates to:

    body {
      margin: 0vh 0vw;
    }
    
    .header {
      position: relative;
      width: 100%;
      height: 12vh;
      background-color: #004d40;
      display: flex;
      align-items: center;
      justify-content: center;
      overflow: hidden;
      top: 0;
    }
    
    .line {
      position: absolute;
      left: 0;
      top: calc(50%);
      width: 100%;
      height: 0.25vh;
      background-color: white;
      z-index: 1;
    }
    
    svg {
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, 0%);
      z-index: 2;
    }
    <!DOCTYPE html>
    <html lang="tr">
    
    <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>SVG Header with Half Circle</title>
    </head>
    
    <body>
    
      <div class="header">
        <div class="line"></div>
        <svg width="10vw" height="5vh" viewBox="0 0 100 50" preserveAspectRatio="xMidYMin meet" xmlns="http://www.w3.org/2000/svg">
            <path d="M0,0 A50,50 0 0,0 100,0" fill="#004d40" stroke="white" stroke-width="3"/>
        </svg>
      </div>
    
    </body>
    
    </html>