当前位置: 动力学知识库 > 问答 > 编程问答 >

html - Positioning elements in a grid

问题描述:

You need to have several 200px wide DIVs (.item) inside a 620px wide DIV (.container).

  • The .container DIV should fit 3 .item DIVs in a row.
  • The .item DIVs should be exactly 10px away from each other.
  • There should be no space between the border of the .container DIV and the .item DIVs immediately next to it.

See the figure bellow for a better understanding.

How would you achieve it - margins, a table...?

网友答案:

you can try the following, but this way you will have to add a 'mask', but no need for css3, nor adding/removing classes depending on where the item is (in other words, no need for any type of scripts, just pure html/css):

HTML:

<div class='mask'>
    <div class='container'>
        <div class='item'></div>
        <div class='item'></div>
        <div class='item'></div>
        <div class='item'></div>
    </div>
</div>

CSS:

 .mask{border:10px solid #ddd;width:620px;overflow:hidden}
 .container{width:630px;background-color:#333;margin-top:-10px;overflow:hidden;float:left}
 .item{float:left;margin-right:10px;width:200px;height:100px;background-color:#4a6b82;margin-top:10px}

Try here : Demo

网友答案:

No need for a table. Unless it's tabular data, that is.

Float each div, give it the desired width and margin, and make sure the last div in the row doesn't have this margin. You can accomplish this using a class, or using the css :nth-child(3) pseudo selector. Because of the lack of support for this selector I would recommend a class for it.

One more thing: this works fine if all div's have equal heights. If they don't, you may encounter some weird positioning across various browsers. The best way to work around this is to put the three div's of each row in a row div.

HTML:

<div class="container">
  <div class="row">
    <div class="item"/>
    <div class="item"/>
    <div class="item last"/>
  </div>
  <div class="row">
    <div class="item"/>
    <div class="item"/>
  </div>
</div>

CSS:

.item { float: left; width: 200px; margin-right: 10px; }
.last { margin-right: 0; }
分享给朋友:
您可能感兴趣的文章:
随机阅读: