Home > Article > Web Front-end > How to Center a Container and Left-Align Child Elements in a Responsive Grid?
You desire to display images in a responsive grid, centering them horizontally and aligning them left within each row, while maintaining a fixed distance between them. The images should wrap automatically as the browser window resizes to fit the maximum number per row without altering their size.
Achieving the desired layout solely with CSS can be challenging. Here's an approach that leverages media queries to adjust the width of inner divs based on viewport dimensions:
<code class="css">body { margin: 10px 0; } .outer { text-align: center; } .inner { font-size: 0; /* fox inline gaps */ display: inline-block; text-align: left; } .item { font-size: 16px; /* reset font size */ display: inline-block; margin: 5px; /* gutter */ } .item img { vertical-align: top; } @media (max-width: 551px) { /* ((100+5+5)x5)+1 */ .inner { width: 440px; /* (100+5+5)x4 */ } } @media (max-width: 441px) { .inner { width: 330px; } } @media (max-width: 331px) { .inner { width: 220px; } } @media (max-width: 221px) { .inner { width: 110px; } }</code>
<code class="html"><div class="outer"> <div class="inner"> <div class="item"><img src="//dummyimage.com/100"></div> <div class="item"><img src="//dummyimage.com/100"></div> <div class="item"><img src="//dummyimage.com/100"></div> <div class="item"><img src="//dummyimage.com/100"></div> <div class="item"><img src="//dummyimage.com/100"></div> </div> </div></code>
The above is the detailed content of How to Center a Container and Left-Align Child Elements in a Responsive Grid?. For more information, please follow other related articles on the PHP Chinese website!