简体   繁体   English

使子元素在父容器中溢出

[英]Make child elements overflow in parent container

How do I make child elements overflow if their width is greater than parent's width?如果子元素的宽度大于父元素的宽度,如何使子元素溢出?
As you can see, below in the code the .container width is 600px while every div inside has width 200px, so the total width is 1200px.正如你所看到的,在下面的代码中, .container的宽度是 600px,而里面的每个 div 的宽度都是 200px,所以总宽度是 1200px。 Why aren't the divs inside .container overflow?为什么.container中的 div 没有溢出?

 * { margin: 0; padding: 0; box-sizing: border-box; } .container { width: 600px; padding: 1rem; display: flex; overflow-x: auto; border: 1px solid red; } .container div { width: 200px; height: 50px; border: 1px solid black; display: flex; justify-content: center; align-items: center; }
 <body> <div class="container"> <div>child</div> <div>child</div> <div>child</div> <div>child</div> <div>child</div> <div>child</div> </div> </body>

Don't use width .不要使用width

Use flex properties on the children and max-width on the container.在子节点上使用 flex 属性,在容器上使用max-width

 * { margin: 0; padding: 0; box-sizing: border-box; } .container { max-width: 600px; padding: 1rem; display: flex; overflow-x: auto; border: 1px solid red; } .container div { flex: 0 0 200px; height: 50px; border: 1px solid black; display: flex; justify-content: center; align-items: center; }
 <body> <div class="container"> <div>child</div> <div>child</div> <div>child</div> <div>child</div> <div>child</div> <div>child</div> </div> </body>

Use min-width on child divs instead of width .在子 div 上使用min-width而不是width

 * { margin: 0; padding: 0; box-sizing: border-box; } .container { width: 600px; padding: 1rem; display: flex; overflow-x: auto; border: 1px solid red; } .container div { min-width: 200px; height: 50px; border: 1px solid black; display: flex; justify-content: center; align-items: center; }
 <body> <div class="container"> <div>child</div> <div>child</div> <div>child</div> <div>child</div> <div>child</div> <div>child</div> </div> </body>

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

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