简体   繁体   中英

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. Why aren't the divs inside .container overflow?

 * { 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 .

Use flex properties on the children and max-width on the container.

 * { 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 .

 * { 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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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