Home > Web Front-end > CSS Tutorial > How to Left-Align the Last Row of a Centered Inline-Block Grid Using Only CSS?

How to Left-Align the Last Row of a Centered Inline-Block Grid Using Only CSS?

Susan Sarandon
Release: 2024-12-02 20:57:12
Original
500 people have browsed it

How to Left-Align the Last Row of a Centered Inline-Block Grid Using Only CSS?

Left Aligned Last Row in Centered Grid of Elements

This question addresses the challenge of aligning the last row of a grid of inline-block elements to the left while maintaining the centered alignment of the entire grid. The user is specifically looking for a CSS solution that doesn't involve Flexbox or additional markup.

Here's an adaptive grid solution that meets the requirements:

html, body {
    margin:0;
    padding:0;
}
#container{
    font-size:0;
    margin:0 auto;
    width:1000px;
}
.block {
    font-size:20px;
    width: 150px;
    height: 150px;
    margin:25px;
    background: gold;
    display:inline-block;
}

@media screen and (max-width: 430px) {
    #container{
        width:200px;
    }
}

@media screen and (min-width: 431px) and (max-width: 630px) {
   #container{
        width:400px;
    }
}
@media screen and (min-width: 631px) and (max-width: 830px) {
   #container{
        width:600px;
    }
}
@media screen and (min-width: 831px) and (max-width: 1030px) {
   #container{
        width:800px;
    }
}
Copy after login
<div>
Copy after login

In this solution, the inline-block elements are placed inside a container with a fixed width. As the width of the browser window changes, the container resizes while maintaining its centered position. When the container's width becomes too narrow to accommodate all the elements, they start wrapping to the next line. The last line is automatically left-aligned due to the default behavior of inline-block elements.

Demo Link:

[Adaptive Grid Demo](Insert Demo Link Here)

By resizing the browser window, you can observe how the grid adapts and the last row remains left-aligned in all scenarios.

The above is the detailed content of How to Left-Align the Last Row of a Centered Inline-Block Grid Using Only CSS?. 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