Search code examples
htmlcssoverflowzoomingmargin

Margin-Top < 0 leads to wrong zooming


I want a child element to be zoomable and centered. If you change the zoom of the child to 200% you can see that the element's top is violet, but you can't zoom up. How can I fix this? I think it's because the margin-top is below zero.

Zoom 100% :

#child {
  background-image: linear-gradient(red, violet, yellow, green, pink);
  width:50px;
  height:400px;
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    margin: auto;
    zoom: 100%;
}

#parent {
  background-color:blue;
  width:500px;
  height:500px;
  position: relative;
  transform: scale();
  overflow: auto;
}
<div id="parent">
  <div id="child"></div>
</div>

Zoom 200% :

#child {
  background-image: linear-gradient(red, violet, yellow, green, pink);
  width:50px;
  height:400px;
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    margin: auto;
    zoom: 200%;
}

#parent {
  background-color:blue;
  width:500px;
  height:500px;
  position: relative;
  transform: scale();
  overflow: auto;
}
<div id="parent">
  <div id="child"></div>
</div>


Solution

  • Solved this by adding 'display: flex; align-items: center;' to the parent and removing the position absolute (incl. positions)

    #child {
      background-image: linear-gradient(red, violet, yellow, green, pink);
      width: 50px;
      height: 400px;
      margin: auto;
      zoom: 200%;
    }
    
    #parent {
      background-color:blue;
      width: 500px;
      height: 500px;
      overflow: auto;
      display: flex;
      align-items: center;
    }
    <div id="parent">
      <div id="child"></div>
    </div>