Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Displaying elements in multiple rows using CSS

Tags:

html

css

I have a fixed width container <div> that displays one or more widget <div>s. I want it to look like this:

rows in CSS <- grey blocks are widgets, red border is the container

Simplified, my structure in HTML looks like this:

<div id="container">
    <div id="widget1">1</div>
    <div id="widget2">2</div>
    <div id="widget3">3</div>
    <div id="widget4">4</div>
    <div id="widget5">5</div>
    <div id="widget6">6</div>
    <div id="widget7">7</div>
</div>

Considerations

  1. Widgets will have a fixed height e.g. 100px
  2. Widgets will have a fixed width e.g. 100px but they may also be a multiple of that width (plus any margins crossed - see widget 1)
  3. Widgets should be spaced nicely with a margin (or similar) e.g. 10px
  4. I don't know how many widgets there will be (the user can assign as many or few as they like to the container).
  5. The container is a fixed width but doesn't have any "visual" styling (the red border is there for demonstration)
  6. Solution has to work in modern browsers (and MSIE7) and would ideally be pure CSS.

Because of consideration 4. I can't assign additional markup e.g. row div, classes (.first-child, .last-child) and because of 2. :nth-child wouldn't work AFAIK.

Things I've tried

margin-left on widgets with :first-child setting margin-left: 0 won't display a new row properly.

margin-right on widgets with :last-child setting margin-right: 0 the first row forces the container div wider and last-child isn't supported until MSIE9.

equal left and right margins (e.g. margin: 0 5px 10px) forces the container wide again.

overflow - works great in my head! Not so much with either margins or padding.

Is there a way to do this in CSS?

http://jsfiddle.net/agtb/VHXGT/

like image 433
agtb Avatar asked Oct 22 '11 13:10

agtb


1 Answers

I believe you are thinking too complicated :-)

If I understand you correctly you don't need any special handling of the separate widgets. Just give the widgets an all around margin of half the spacing, and the container the same margin but negative.

#container {
    width: 440px;
    margin: -5px;
}

#container div {
    background-color: gray;
    height: 100px;
    width: 100px;
    float: left;
    margin: 5px;
}

See http://jsfiddle.net/SGdG3/1/

like image 186
RoToRa Avatar answered Oct 08 '22 17:10

RoToRa