0

How do I ensure that items in a container are centered regardless of screen size?

I am trying to create a responsive/dynamic layout on a web-page that has a container div and some results/items (divs) inside. I would like them to flow within the available width but have uniform margin/alignment within the centered div which I am struggling to achieve. Here are three images of what I want to achieve. This could be a desktop, a tablet and a phone:

Desktop Tablet mobile

So far I've had to go with a cut-off width of e.g. 800px and two different layouts, but that's not optimal. The container should be dynamic, for example 90% width but the items inside fixed width of 200px. I can use flow:left; or display:inline-block; to flow the items inside, but they will always be left aligned, so that when one "slides" down to the next line, the remaining are sitting to the left with a gap to the right.

This is probably a common use case, and I'm happy to be referred to other answers, but I haven't been able to search correctly in order to find the answer.

EDIT: I know that I can do this with JavaScript. I could probably use getBoundingClientRect on the container and with code adjust the margin of the items, but there must be a CSS solution :)

jcmiller
  • 51
  • 4
  • it's not possible with css (unless you use media queries for the specific break points of when they wrap) as once your items wrap, you will always get the remaining space on the right – Pete Dec 01 '22 at 10:29
  • it's possible, I have updated the duplicates – Temani Afif Dec 01 '22 at 11:39

0 Answers0