首页 > 解决方案 > 为什么父级上的 CSS 溢出属性会影响 IMG 子级的大小?

问题描述

以下正是我想要的,但我不明白为什么,这让我很恼火。

我想:

<!DOCTYPE html>
<html>
  <head>
    <style>
      .root {
        width: 500px;
        height: 500px;
      }
      .flex-container {
        display: flex;
        flex-direction: column;
        background-color: red;
        height: 100%;
        width: 100%;
      }
      .first {
        background-color: blue;
      }
      .second {
        background-color: darkmagenta;
        flex-grow: 1;
        display: flex;
        flex-direction: column;
        overflow: hidden;
      }
      .wrap {
        height: 50%;
        width: 100%;
      }
      img {
        height: 100%;
        width: 100%;
      }
    </style>
  </head>
  <body>
    <div class="root">
      <div class="flex-container">
        <div class="first">
          This div should be sized accoring to it's content and wrap if needed
          which it does, nice!
        </div>
        <div class="second">
          <div class="wrap">
            <img
              src="https://www.publicdomainpictures.net/pictures/30000/velka/cat-13476279941Ls.jpg"
            />
          </div>
          <div class="wrap">
            <img
              src="https://www.publicdomainpictures.net/pictures/30000/velka/cat-13476279941Ls.jpg"
            />
          </div>
        </div>
      </div>
    </div>
  </body>
</html>

在试验和弄乱之后,我得到了这个 HTML 和 CSS。关键是overflow: hidden;"second" div。没有它,孩子img会显示得更大,"second" div超出其父母。

我不明白如何overflow: hidden;影响孩子的大小 - 我原以为他们会被剪掉。任何指针?

标签: htmlcssflexbox

解决方案


我在这篇文章中找到了一个更好的方法:flex child is grow out of parent

该帖子没有放在父母身上,而是overflow: hidden;建议设置min-height: 0;允许其孩子缩小并变得比他们的内容更小。

这对我来说更有意义。

编辑发现这篇文章更详细,还有一个解释了这一切的 flexbox 规范的链接:为什么 flex 项目不缩小超过内容大小?

在主轴上可见溢出的弹性项目上,当在弹性项目的主轴最小尺寸属性上指定时,指定自动最小尺寸。否则计算为 0。


推荐阅读