居中网格 - 内部网格左对齐 - 没有Javascript - 没有媒体查询

时间:2014-08-19 17:31:36

标签: html css grid-layout

[编辑]

我正在寻找没有javascript的解决方案,并且没有媒体查询(用户可以更改容器大小)。

[/编辑]

我需要创建一个项目网格。

  1. 容器宽度灵活。
  2. 网格始终居中
  3. 网格内的项目需要左对齐
  4. 非常简单,但我无法找到解决方案!!

    这是一张展示我需要的图片:

    enter image description here

    这是一个jsfiddle:http://jsfiddle.net/5e4bcc9L/1/

    HTML:

    <div class="container">
        <div class="grid"> 
             <a href="#"></a>
             <a href="#"></a>
             <a href="#"></a>
             <a href="#"></a>
             <a href="#"></a>
             <a href="#"></a>
             <a href="#"></a>
        </div>
    </div>
    

    CSS:

    .container {
        width: 100%;
        background-color:#CCC;
        text-align: center;
    }
    .grid {
        background-color:#999;
        display: inline-block;
        text-align: left;
    }
    a {
        display:inline-block;
        height: 100px;
        width: 100px;
        background-color:#000;
        margin: 5px;
    }
    

1 个答案:

答案 0 :(得分:1)

鉴于您不想使用JavaScript或媒体查询,很难以您想要的方式实现。问题在于您在网格中设置块的精确高度和宽度。我会解释更多:

<强> Centered grid with left alignment

CSS(保持HTML相同)

.container{
    width: 100%; 
    height:100%;
    background-color:#CCC;
    text-align:center;
}

.grid{
    background-color:#999; 
    display: inline-block;
    position:relative;
    width: 80%;
    border:1px solid black;
}

.grid a{
    display:inline-block; 
    height: 100px; 
    width: 100px; 
    background-color:#000;
    margin: 5px;
    float:left;
}

.ghost{clear: both;}

如果你看小提琴,它会按你描述的方式工作......直到你调整窗口大小。那是因为网格中的块不能浮动,直到有足够的空间让它们这样做,这会留下一个“不正确”(对你)大小的块。

如果可以删除左对齐标准,那么就中心内容而言,您会获得更愉快的体验 demonstrated here 。只需在上面的CSS中注释掉浮点数,看看我的意思。

否则,上面提到的链接web-tiki可能是最佳选择。