繁体   English   中英

溢出自动不起作用,因为孩子正在使父母变大

[英]Overflow auto doesn't work because children is making parent bigger

我的目标是编写一个包含 2 列的简单设计 - 第一列 250px 宽度,第二列 rest 的可用空间。 第二列内可能是一个巨大的元素,它必须占据父级宽度的 100%,并且如果比父级大,则可以水平滚动。

这是我的 CSS:

.layout {
  display: flex;
  padding: 20px;
}

.sidebar {
  width: 250px;
  background-color: red;
}

.content {
  flex-grow: 1;
  background-color: lightgreen;
}

.largeBox {
  overflow-x: auto;
  max-width: 100%;
}

.large {
  width: 900px;
  height: 50px;
  background: rgb(34, 193, 195);
}

它不起作用,因为它使第一列缩小到它的内容而不是 250px。 当我将其设置为最小宽度时,整个页面都会出现滚动条。 如何实现这个设计? 代码链接: https://codesandbox.io/s/affectionate-meadow-c9txz1

您可以尝试用min-width替换width

.sidebar {
    min-width: 250px;
    background-color: red;
}

 body { margin: 0; }.layout { display: flex; padding: 20px; }.sidebar { flex-shrink: 0; width: 250px; background-color: red; }.content { flex-grow: 1; background-color: lightgreen; max-width: 100%; }.largeBox { overflow-x: auto; max-width: 100%; }.large { width: 900px; height: 50px; background: rgb(34, 193, 195); background: linear-gradient( 106deg, rgba(34, 193, 195, 1) 0%, rgba(253, 187, 45, 1) 35%, rgba(45, 253, 149, 1) 100% ); }
 <body> <div class="layout"> <div class="sidebar"> <p>sidebar</p> </div> <div class="content"> <p>this is epic</p> <div class="largeBox"> <div class="large"></div> </div> <p>Thank you!</p> </div> </div> </body>

您需要在.sidebar中使用flex-shrink: 0

你会考虑换到 CSS Grid 吗? 当您开始使用“fr”单位(即剩余空间)时,您的生活会变得更加轻松。

.layout {
  display: grid;
  grid-template-columns: 250px 1fr;
  overflow: scroll;
}

.sidebar {
}

.content {
}

然后,隐藏滚动条:

scrollbar-width: none; // firefox
&::-webkit-scrollbar { display: none; } // Chrome, Safari and Opera
-ms-overflow-style: none; //IE and Edge

你不需要告诉孩子们跨越什么,父网格会按照你声明的顺序来指导他们。 即侧边栏将是 250px,内容将占用剩余空间 (1fr)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM