html - 使用固定宽度的列在 CSS 网格中居中

标签 html css css-grid centering

我正在尝试制作一个简单的以 CSS 为中心的网格布局。
我知道当我使用 justify-items: center ,网格容器内的元素应该水平对齐,但是当我像这样以像素为单位指定列宽时 grid-template-columns: repeat(3, 100px)整个电网恢复正常。那么有什么方法可以使网格项居中但同时以像素为单位指定列宽?
这是我的例子:

    <div class="container">
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
    </div>
.container {
    background-color: #aa96da;
    display: grid;
    justify-items: center;
    grid-gap: 20px;
    grid-template-rows: repeat(3, 1fr);

    /*Only if I change this 100px to '1fr' the justify-items will work */
    grid-template-columns: repeat(3, 100px);
}

.item {
    width: 100px;
    height: 100px;
    background-color: green;
}

最佳答案

更改 justify-itemsjustify-content它应该工作。

.container {
    background-color: #aa96da;
    display: grid;
    /* justify-items: center; */
    justify-content: center;
    grid-gap: 20px;
    grid-template-rows: repeat(3, 1fr);

    /*Only if I change this 100px to '1fr' the justify-items will work */
    grid-template-columns: repeat(3,  100px);
}

.item {
    width: 100px;
    height: 100px;
    background-color: green;
}
 <div class="container">
    <div class="item"></div>
    <div class="item"></div>
    <div class="item"></div>
    <div class="item"></div>
    <div class="item"></div>
    <div class="item"></div>
    <div class="item"></div>
    <div class="item"></div>
    <div class="item"></div>
</div>

关于html - 使用固定宽度的列在 CSS 网格中居中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61492613/

相关文章:

html - 折叠导航栏中的子菜单项

javascript - 按钮不响应悬停或单击

html - 具有 CSS 网格的等宽侧边栏列

css - 什么是 CSS 网格项的默认起始列?

php - 在多个子目录中使用 php include

java - 如何在 Selenium WebDriver 中获取 "li"类的所有 "ul"元素

javascript - 井字游戏 : Checking Empty Squares

javascript - 响应式菜单不适用于小屏幕

css - 如何创建具有相反 flex 底部的 div

javascript - 附加显示 'undefined'