Would it be possible to center a wrapping CSS grid with fixed-width grid items inside both a desktop and mobile viewport, using Flexbox or CSS Grid? I am aiming toward a solution without resorting to media queries if possible.
Here is the closest I could get to a solution that still wraps using CSS Grid (based on searches for "CSS grid equal width" and similar queries):
html {
height: 100%;
margin: auto;
}
body {
margin: 20px;
place-self: center;
}
nav {
display: grid;
grid-template-columns: repeat(auto-fit, 180px);
grid-gap: 20px;
max-width: 800px;
}
ul {
list-style-type: none;
margin: 0;
padding: 0;
}
<div class="container">
<nav>
<ul>
<li>Link A</li>
</ul>
<ul>
<li>Link B</li>
</ul>
<ul>
<li>Link C</li>
</ul>
<ul>
<li>Link D</li>
</ul>
<ul>
<li>Link E</li>
</ul>
</nav>
</div>
In addition to the above snippet, I have also tried:
- adding
display: gridto thehtmltag - adding
grid-auto-columns: 180px;andgrid-auto-flow: column;to thenavtag
These additions help center the grid inside the viewport, but cause the wrapping to not function properly.
Here is my attempt at a solution using Flexbox (effective, but the list grid doesn't center in viewports smaller than max-width - which I'd desire over the existing left alignment):
html {
display: flex;
place-content: center;
height: 100%;
margin: 0;
}
body {
margin: 20px;
place-self: center;
}
nav {
display: flex;
flex-flow: row wrap;
min-width: 280px;
max-width: 800px;
justify-content: start;
align-content: center;
}
ul {
list-style-type: none;
margin: 0 20px 20px 0;
padding: 0;
width: 180px;
<div class="container">
<nav>
<ul>
<li>Link A</li>
</ul>
<ul>
<li>Link B</li>
</ul>
<ul>
<li>Link C</li>
</ul>
<ul>
<li>Link D</li>
</ul>
<ul>
<li>Link E</li>
</ul>
</nav>
</div>
Here are some of many Stack Overflow threads that I referenced prior to posting: