Center Align Container and Left Align Child Elements
This question aims to display images in a container that is centered on the page, with the images grouped together and displayed one after the other. The challenge lies in maintaining a fixed distance between images while accommodating varying browser window widths.
To achieve this layout using CSS, media queries can be employed to adjust the width of the image-containing div based on the viewport size. The code below demonstrates this approach:
body { margin: 10px 0; } .outer { text-align: center; } .inner { font-size: 0; /* fix for 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; } }
Within the HTML structure:
<div class="outer"> <div class="inner"> <div class="item"><img src="..."></div> <div class="item"><img src="..."></div> <div class="item"><img src="..."></div> </div> </div>
This approach uses media queries to dynamically adjust the inner div's width as the browser window is resized. The width is calculated considering the size of each image and the desired gutter between them. The number of images per row changes automatically based on the browser width.
It's important to note that optimizing the code for performance is recommended if dealing with a large number of images. Additionally, consider using Flexbox or CSS preprocessors for a more flexible solution.
The above is the detailed content of How to Center a Container with Left-Aligned Child Elements and Responsive Images?. For more information, please follow other related articles on the PHP Chinese website!