I’m attempting to dynamically distribute elements in CSS to fit them within a container regardless of the screen size.
To give you an idea of what I’m trying to achieve, this is what I currently have on one device, versus another device with a larger screen size
My expected functionality for this is that the code would see how many items it can fit across the space, spacing them evenly and centralising them within the container, then move to the next line and repeat the operation, fitting as many as it can and centralising. I believe this would distribute them effectively to fit the space, and seems like something relatively simple but I just can’t find what I’m looking for online.
Currently I’m using two container classes, one with three elements and one with two elements, and a fixed width between each element, but obviously that isn’t adequate to solve the problem because sometimes the elements hang outside of the box, this is the CSS that:
.container3 {
display: grid;
grid-template-columns: auto auto auto;
grid-gap: 5rem;
align-self: center;
}
.container2 {
display: grid;
grid-template-columns: auto auto;
grid-gap: 5rem;
align-self: center;
}
I recognise that I’m a novice with CSS, HTML, JavaScript, and website design in general, coming from a background in Python, but I’m hoping to learn a little more to get this to work, so ELI5 is much appreciated 🙂
If it is of any help to solving the problem, the website is powered by MediaWiki as it is a wiki site, so I’m not sure if that changes much.
3
Answers
something like this? with
flex-wrap: wrap
andjustify-content:center
should achieve thatYou should consider using % values or
fr
units instead ofrem
units so the grid gap is relative to the container width (instead of being dependent on the font size of the root element, which leads to the fixed gap size and overflow you’re seeing). You could also adjust the font size similarly.I think what you are looking for is the
flex-wrap
property of CSSSee the below example and you can implement it in your code.