I'm trying to dynamically size a container to the width of its children when they're broken down into columns and rows. This can easily be achieved by writing a bunch of media queries and hard coding the width of the container, but I'm looking for a way to do it dynamically with CSS.
In this example id like .container
to only be a multiple of the width of a fixed size .item
(200px
, 410px
, 620px
, 830px
, etc) and not include the empty space to the right.
.container {
background-color: #555;
display: flex;
flex-wrap: wrap;
gap: 10px;
max-width: 1000px;
padding: 10px;
}
.item {
aspect-ratio: 1;
background-color: #ddd;
width: 200px;
}
<div >
<div ></div>
<div ></div>
<div ></div>
<div ></div>
<div ></div>
<div ></div>
<div ></div>
<div ></div>
<div ></div>
<div ></div>
</div>
CodePudding user response:
If the width of items are fixed you can try like below:
.wrapper {
display: grid;
grid-template-columns: repeat(auto-fill,200px); /* same as width of items */
gap: 10px;
padding: 10px; /* move the padding here */
}
.container {
grid-column: 1/-1; /* take all the columns */
background-color: #555;
outline: 10px solid #555; /* use outline to cover the padding */
display: flex;
flex-wrap: wrap;
gap: inherit;
}
.item {
aspect-ratio: 1;
background-color: #ddd;
width: 200px;
}
<div >
<div >
<div ></div>
<div ></div>
<div ></div>
<div ></div>
<div ></div>
<div ></div>
<div ></div>
<div ></div>
<div ></div>
<div ></div>
</div>
</div>
CodePudding user response:
Try changing .item element width property from px to percentage.
.item {
width: 100%;
}