Centered Grid - Inner Grid align left - NO Javascript - NO Medias Queries

安稳与你 提交于 2019-12-23 20:33:04

问题


[EDIT]

I'm looking for a solution without javascript, and without medias queries (user can change the container size).

[/EDIT]

I need to create a grid of items.

  1. The container has a flexible width.
  2. The grid is always centered
  3. Items inside the grid need to be left aligned

Pretty simple, but I can't find the solution !!

Here is an image that present what I need:

And here is a 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:


Given that you don't want to use JavaScript or media queries, this is tough to achieve exactly the way you want. The problem lies in the fact that you're setting exact heights and widths of your blocks within the grid. I'll explain more:

Centered grid with left alignment

CSS (keeping HTML the same)

.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;}

If you look at the fiddle, it works the way you described...until you resize the window. That's because the blocks in the grid can't float until there's enough space for them to do so, which leaves you with an "incorrectly" (to you) sized block.

If the left alignment standard can be dropped, you get a much more pleasant experience as far as centered content is concerned as demonstrated here. Simply comment out the float in the CSS above to see what I mean.

Otherwise, the link web-tiki gave above is probably the best option.



来源:https://stackoverflow.com/questions/25389534/centered-grid-inner-grid-align-left-no-javascript-no-medias-queries

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!