简体   繁体   English

如何将 div 网格居中(纯 JS 和 CSS)

[英]How can I center a grid of divs (pure JS and CSS)

I'm making a pixel art maker where the user can input their own grid dimensions.我正在制作一个像素艺术制作器,用户可以在其中输入自己的网格尺寸。 I've got the grid to make itself, but I have two issues.我有自己的网格,但我有两个问题。 First, I can't seem to center my grid.首先,我似乎无法将网格居中。 My grid is made up of multiple divs.我的网格由多个 div 组成。 I've tried:我试过了:

grid-square {
   margin: auto;
}

But that spaces out all of the grid divs from each other.但这会将所有网格 div 彼此隔开。 I can't get anything else to work.我不能让任何其他工作。 Any suggestions?有什么建议?

https://jsfiddle.net/2L3hjfba/2/ https://jsfiddle.net/2L3hjfba/2/

PS聚苯乙烯

Also, if the grid is too big, it makes the divs overlap, so any help with that is also appreciated!此外,如果网格太大,它会使 div 重叠,因此也非常感谢任何帮助!

I've found the answer!我找到了答案! Each row of the grid technically took up the entire length of the container.从技术上讲,网格的每一行都占据了容器的整个长度。 So, I simply needed to display the rows as flex and set justify-content to center to center the whole grid.所以,我只需要将行显示为 flex 并将 justify-content 设置为 center 以将整个网格居中。

Try This!尝试这个!

.row {
    justify-content: center;
}

This will help you out to center the canvas.这将帮助您将画布居中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM