简体   繁体   中英

Prevent DIVs from wrapping within parent

I run in to this problem quite often, and it usually results in me spending additional time to try and address the problem. Essentially it is a straightforward layout as follows:

HTML:

<div id="container">
  <div id="items">
    <div class="item">
      (data here)
    </div>
    <div class="item">
      (data here)
    </div>
    <div class="item">
      (data here)
    </div>
    <div class="item">
      (data here)
    </div>
    -- repeats --
  </div>
</div> <-- end container -->

CSS

#container {
  margin: 0 auto;
  width: 980px;
  overflow: hidden;
}
#items {
  float: left;
  width: 980px;
  min-height: 1000px;
}
#items .item {
  float: left;
  width: 230px;
  height: 230px;
  margin-right: 20px;
  margin-bottom: 20px;
}

My intended result is to have a 4 x 4 grid displaying items. As you can see from my CSS above, I am adding a right margin to each item in order to space them out. The only problem with this is that the fourth item in each row drops down to the next row (which is obviously being caused due to the right margin on the item):

(230 x 4) = 920 + (20 x 4) = 80 = 1000 (but the container width is 980). So instead of 4 items on each row I get three.

If the right margin on every fourth item isn't included then all four items fit perfectly within the constraints of the parent DIV. I know I can just add a separate class for the fourth item and set it's right margin to 0px but this means I have to add additional checks in my scripting when displaying products dynamically.

Ideally what I would like is a pure CSS solution that works well in all major browsers AND IE7. Does anybody know of any?

You could try using percentages rather than fixed widths for your items .

#items .item {
    float: left;
    width: 23%;
    height: 230px;
    margin-right: 2%;
    margin-bottom: 20px;
}

Fiddle: http://jsfiddle.net/kboucher/Mv7sh/

To target every fourth child of an element you can use :nth-child(x) , but that is not supported in IE8 and earlier. w3schools doc

:last-child won't really do it because you would have to wrap every group of four.

However, depending on your design, a width and height of 225 instead of 230 would even out at 980 with the margins.

And unless you have a specific reason to only have margin-right, you could split it into margin-right and margin-left with a value of 10 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM