Search code examples
htmlcssflexboxcenter

Items not staying in center of div on resize or not, keeps going offset


Ive been trying to fix this issue for a pretty long time now, but for some reason, whenever I resize the page, this one div goes offset and fails to stay in the center. I made the text in the div unwrapped on purpose so that it doesnt interfere with the elements I will be adding later.

I already tried using margin: 0 auto, justify-content: center; and align-items: center; on every element and off every element, experimenting to see which one would center it properly but none of them worked. I also tried using a 100% width parent element but that didn't work either.

I wouldn't want to use javascript in this case if just css is possible. If javascript is the best way to fix it then so be it.

Here is a JSFiddle that shows the issue


Solution

  • It's already on center, for horizontally center margin: 0 auto is working as expected. The problem is in the child content, where you have fixed with (which is more than parents), that's why it's going offscreen.

    You can add overflow: hidden on parent which have margin: 0 auto to see it's on center.

    For children, remove fixed width and/or min-width, here you can use % instead of px for width.