开发者

Positioning elements in a grid

开发者 https://www.devze.com 2023-02-04 19:57 出处:网络
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.

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...?

Positioning elements in a grid


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

精彩评论

暂无评论...
验证码 换一张
取 消