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 >
<div>child</div>
<div>child</div>
<div>child</div>
<div>child</div>
<div>child</div>
<div>child</div>
</div>
</body>
CodePudding user response:
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 >
<div>child</div>
<div>child</div>
<div>child</div>
<div>child</div>
<div>child</div>
<div>child</div>
</div>
</body>
CodePudding user response:
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 >
<div>child</div>
<div>child</div>
<div>child</div>
<div>child</div>
<div>child</div>
<div>child</div>
</div>
</body>