How to Center a Container and Left-Align Child Elements in a Responsive Grid?

Mary-Kate Olsen
Release: 2024-11-01 17:34:02
Original
541 people have browsed it

How to Center a Container and Left-Align Child Elements in a Responsive Grid?

Center-align Container and Left-align Child Elements

Issue

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.

Solution

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

<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>
Copy after login
<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>
Copy after login

Considerations

  • Consider using JavaScript for large numbers of items.
  • CSS preprocessors can enhance code reusability.
  • Adjust media query breakpoints as needed to suit your requirements.

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!