wakey
wakey

Reputation: 2409

Make tables overflow to new line if max-width reached?

I am trying to design a table which will display data pulled from a database in somewhat of a graphical form. I would love for the table to have the functionality to overflow to the next line when the collective 'td's have reached a max-width that is set by the table.

Example: table width set to 30% (lets say for argument's sake thats 100px) and the tds have a width of 10px. When there have been 11 tds entered, the 11th moves to a newline and continues displaying there.

Here is what I have so far:

HTML:

<table>
    <tr>
        <td></td>
        <td class='green'></td>
        <td class='green'></td>
        <td></td>
        <td></td>
        <td class='green'></td>
        <td class='green'></td>
        <td class='green'></td>
        <td></td>
        <td></td>    
        <td></td>
        <td></td>
        <td></td>
        <td class='green'></td>
        <td class='green'></td>
    </tr>
</table>

CSS:

td{
    width:10px;
    height:10px;
    border: 1px solid black;
}
table{
    max-width:30%;
}

.green {
    background:green;
}

Link to fiddle: http://jsfiddle.net/hDsts/160/

Currently, if another <td> is added it just resizes all of them to fit within the max-width set by the table. I want it to overflow to the next line.

Any suggestions on how to solve this problem or of other ways I could accomplish this goal?

Upvotes: 2

Views: 11701

Answers (2)

michael
michael

Reputation: 686

You can set the TD's to display: inline-block; But you're also going to need to specify a width for the table to conform to otherwise it will be 30% of the window width. eg. wrap it in in a div with a specify width.

http://jsfiddle.net/hDsts/160/

Upvotes: 2

GomatoX
GomatoX

Reputation: 400

I think it is impossible to do it only with css and html, I prefer you to use display: flex to achieve your goal.

HTML:

<div class="holder">
  <div class="item"> 1 </div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"> Last element </div>
</div>

CSS:

.holder {
  max-width: 30%;
  background-color: #ccc;
  display: -webkit-flex;
  display: flex;
  -webkit-flex-direction: row;
  -webkit-flex-wrap: wrap;
  font-size: 12px;
}
.item {
  width: 100px;
  border: 1px solid #000;
  height: 20px;
  flex: 80px 1;
  text-align: center;
  color: #000;
}

So minimal width of item would be 80px.

Here is working example: http://codepen.io/GomatoX/pen/Ceonj

Upvotes: 3

Related Questions