When I'm using height: auto; while using grid in CSS, the height of the element is set to the maximum height of an element in that row, so, if an element is really small, the length of the card div it is in will be increased, but that part will be empty. I want to bypass that behaviour and somehow set the height of the element to the actual height of the element if the height was only as big as the elements inside it using Javascript. How can I do this?
NOTE: If you have an idea of an approach that might be better than mine, you are welcome to share it. I do not know whether what I am doing is the best approach, so you can recommend other ways to do this (if it is within the confines of HTML, CSS, and Javascript)
EDIT:
@SebastianSimon posted this in the comments of this question: height: min-content. This worked, only now there is a gap in my grid row because one element in that row is really long, so now there's a gaping hole there and nothing seems to want to come and fill that space...
CodePudding user response:
Based on your description, I think you need a masonry-layout:
const container = document.getElementById('container');
(function(container) {
let html = ''
for (let i = 0; i < 18; i ) {
const h = 50 10 * i;
html = `
<div style="height: ${ h }px;line-height: ${ h }px">${i}</div>
`
}
container.innerHTML = html
})(container);
body {
margin: 0;
padding: 1rem;
}
.masonry-with-flex {
display: flex;
flex-direction: column;
flex-wrap: wrap;
max-height: 1000px;
}
.masonry-with-flex div {
width: 150px;
background: #EC985A;
color: white;
margin: 0 1rem 1rem 0;
text-align: center;
font-family: system-ui;
font-weight: 900;
font-size: 2rem;
}
<div id="container" ></div>
More solutions here
EDIT
Another approach could be:
const cards = document.querySelectorAll(".card");
(function() {
cards.forEach((card, i) => {
card.style.height = 50 i * 10 "px"
})
})();
.container {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 10px;
}
.column {
display: flex;
flex-direction: column;
gap: 10px;
}
.card {
width: 100%;
display: flex;
align-items: center;
justify-content: center;
box-sizing: border-box;
background-color: rgba(255, 165, 0, 0.3);
border: 1px solid rgba(255, 165, 0, 0.8);
}
<div id="app" >
<div >
<div >A</div>
<div >D</div>
</div>
<div >
<div >B</div>
<div >E</div>
</div>
<div >
<div >C</div>
<div >F</div>
</div>
</div>
