首页 > 解决方案 > CSS 溢出 - 图像不会完全显示在可滚动容器中

问题描述

我有一个在容器内居中的图像,但是当我增加图像的宽度/高度时,它不会完全显示在容器内。

但是当图像不居中(左上角)时,图像会完全显示。为什么会这样?

 

const scaleUp = () => {
  const img = document.getElementById("tree")
  img.style.height = "100%"  
}

const scaleDown = () => {
  const img = document.getElementById("tree")
  img.style.height = "50%"  
}
 .container {
      width: 500px;
      height: 500px;
      background: #f2d0d0;
      overflow: auto;
      margin-bottom: 20px;
      display: flex;
      justify-content: center;
      align-items: center;
    }

    #tree {
      height: 100%;
      border: 1px solid cyan;
    }

    span {
      width: 200px;
      height: 40px;
      border: 1px solid #333;
      padding: 10px;
      cursor: pointer
    }
<div class="container">
    <img id="tree" src="https://momentum.photos/img/843956cc-70c7-4578-97d5-e95102c0a7e2.jpg" />
</div>

<span onClick="scaleUp()" id="scale_up">scale up</span>
<span onClick="scaleDown()" id="scale_up">scale down</span>

标签: htmlcss

解决方案


Height:100%在您的 #tree 选择器上影响您的布局。下面的 CSS 可能会对您有所帮助。

#tree {
 border: 1px solid cyan;
 max-width: 100%;
 height: auto;
 //object-fit: cover; /*uncomment it if you want to fit image in container*/
}

推荐阅读