I'm looking to create a page filled with fixed-size tiles that cover the entire page, ensuring that as many tiles as possible are displayed in one row. If the tiles can't fit without horizontal scrolling, they should be pushed to the next row.
To achieve this layout, I used CSS properties like display: grid
and
grid-template-columns: repeat(auto-fit, 210px)
on the container element. However, I ran into an issue where if the window width is not a multiple of the tile's width, there is empty space on the right side of the screen.
I want to center these tiles on the page, but simply adding auto margins or padding did not work. Can you suggest a straightforward way to accomplish this using only CSS?
Here's the code for the page:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Page</title>
<style>
body {
text-align: center;
}
main {
display: grid;
grid-gap: 10px;
grid-template-columns: repeat(auto-fit, 210px);
}
section {
padding: 5px;
background-color: #F3F3F3;
}
</style>
</head>
<body>
<main>
<section>Tile 01</section>
<section>Tile 02</section>
...
<section>Tile 16</section>
</main>
</body>
</html>
Screenshots:
Tiles with ideal window width: https://i.sstatic.net/3m5JZ.png
Narrow window width without centering: https://i.sstatic.net/6ALZk.png
Desired centering with narrow window:
https://i.sstatic.net/LAJII.png
Done with margin: 0px 9% 0px 9%
,
margin: 0px auto 0px auto
doesn't work.