创建没有div容器的CSS网格

时间:2015-10-02 09:11:00

标签: html css grid

Hello stackoverflowers,

我有这段HT​​ML代码:

<div class="container">
    <div class="block row1 column1"></div>
    <div class="block row1 column2"></div>
    <div class="block row1 column3"></div>
    <div class="block row2 column1"></div>
    <div class="block row2 column2"></div>
    <div class="block row2 column3"></div>
    <div class="block row3 column1"></div>
    <div class="block row3 column2"></div>
    <div class="block row3 column3"></div>
</div>

如何在不更改html的情况下使用css从div创建3x3网格?

亲切的问候,丹尼斯

编辑:有人知道如何将块保持为正方形并居中。例如,容器为700px x 700px,块为100px x 100px。

2 个答案:

答案 0 :(得分:1)

这应该这样做:

.block {
    float:left;
    width:33.3%;
    box-sizing:border-box;
    margin:0;
}

float让div彼此相邻,宽度为1/3。

修改

如果您希望块为矩形,则需要设置宽度和高度。

让我们举个例子:

.container {
    width:700px
}
.block {
    float:left;
    width:100px;
    height:100px;
    box-sizing:border-box;
    margin:0;
}

现在,连续将有7个块,因为块的宽度为100px,容器宽度为700px。如果你想让它们每行3个,你可以添加这个CSS:

.block:nth-child(4n+4) {
    clear:left;
}

或者:

.column1 {
    clear:left;
}

答案 1 :(得分:0)

解决这两个问题 -

<h1>3x3 Grid</h1>
<div class="container">
    <div class="block row1 column1">1</div>
    <div class="block row1 column2">2</div>
    <div class="block row1 column3">3</div>
    <div class="block row2 column1">4</div>
    <div class="block row2 column2">5</div>
    <div class="block row2 column3">6</div>
    <div class="block row3 column1">7</div>
    <div class="block row3 column2">8</div>
    <div class="block row3 column3">9</div>
</div>

<h1>Centered box with 100px x 100px</h1>
<div class="container container2">
    <div class="block row1 column1">1</div>
    <div class="block row1 column2">2</div>
    <div class="block row1 column3">3</div>
    <div class="block row2 column1">4</div>
    <div class="block row2 column2">5</div>
    <div class="block row2 column3">6</div>
    <div class="block row3 column1">7</div>
    <div class="block row3 column2">8</div>
    <div class="block row3 column3">9</div>
</div>

.container *{
    box-sizing: border-box;
}
.container{
    width:700px;
    box-sizing: border-box;
}

.container:after{
    display:block;
    clear:both;
    content:"";
}
.block {
    float:left;
    width:33.3%;
    box-sizing:border-box;
    margin:0;
}

.container2{
    text-align:center;
}
.container2 .block{
    float:none;
    position:relative;
    height:100px;
    width:100px;
    display: inline-block;
}

我猜你的两个问题都得到了答案。