首页 > 解决方案 > 调整页面大小时如何在 CSS 中将这些框居中?

问题描述

我有以下箱子(文章)

在此处输入图像描述

当我尝试调整页面大小时,它变成了这样:

在此处输入图像描述

我希望它在调整窗口大小时自动居中以避免右侧的巨大间隙,但它需要与它已经采用相同的格式。基本上只需将整个组移动到中心而不使单个框居中,因为我希望它们像图片中所示那样浮动到左侧。

编辑:这就是我所追求的:

在此处输入图像描述

这是我当前的CSS:

* {
    margin: 0;
    padding: 0;
}

html, body {
    height: 100%;
}

.container {
    width: 90%;
    height: 100%;
    overflow: hidden;
    background: skyblue;
    margin: auto;
    padding: 20px;
}

.container article {
    float: left;
    width: 250px;
    height: 250px;
    background: blue;
    margin: 25px
}

和我的html:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>Shop</title>
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <link rel="stylesheet" href="css/style.css">
    </head>
    <body>
        <div class="container">
            <article>
                <h2>Hello</h2>
            </article>
            <article>
                <h2>Hello</h2>
            </article>
            <article>
                <h2>Hello</h2>
            </article>
            <article>
                <h2>Hello</h2>
            </article>
            <article>
                <h2>Hello</h2>
            </article>
        </div>
    </body>
</html>

标签: htmlcss

解决方案


使用 flex,卢克

display: flex;
flex-wrap: wrap;
justify-content: center;

* {
    margin: 0;
    padding: 0;
}

html, body {
    height: 100%;
}

.container {
    width: 90%;
    height: 100%;
    overflow: hidden;
    background: skyblue;
    margin: auto;
    padding: 20px;
    display: flex;
    flex-wrap: wrap;
    justify-content: center;
}

.container article {
    width: 250px;
    height: 250px;
    background: blue;
    margin: 25px
}
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>Shop</title>
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <link rel="stylesheet" href="css/style.css">
    </head>
    <body>
        <div class="container">
            <article>
                <h2>Hello</h2>
            </article>
            <article>
                <h2>Hello</h2>
            </article>
            <article>
                <h2>Hello</h2>
            </article>
            <article>
                <h2>Hello</h2>
            </article>
            <article>
                <h2>Hello</h2>
            </article>
        </div>
    </body>
</html>


推荐阅读