Creating three-column table with CSS only? (No table element)

社会主义新天地 提交于 2019-12-06 03:55:13

Using an unordered list is not a BAD method, and the benefit of this is that devices or browsers with CSS disabled (yep, you'll be surprised) will degrade gracefully into a legible list. If you wanted the above to display in a 3 column layout with each row on a new "line" I would try something like this for your css:

First give your ul an ID attribute, so in our case we'll call it <ul id="fakeTable">, and then we can style our li elements to act as table cells:

#fakeTable, #faketable li{
  list-style-type:none; //no bullets etc
  margin:0;
  padding:0;
  }

#fakeTable{
  width:800px; //you could set it to any width really, just an example
  }

#fakeTable li{
  display:block;
  float:left;
  clear:none;
  width:200px;
  padding:0 11px 0 11px;
  }
  • Now assuming your <ul> is 800px wide, the <li> elements will wrap to the next line from 4 to 6, 7 to 9 etc as there is no more space to float a 4th one on each row.

  • If you do not have a set width, convert the widths to %, you could have the <li> width set to 33% - with no <li> padding of course - which will give you a width of 99% across 3 <li> elements, so no space for a 4th, and it will wrap to the next line!

I'd go for 3 divs, each containing one column, give them a min-width and a max-width, and display: inline-block. If the screen is large enough to accommodate them next to each other, they'll be laid out as 3 columns, otherwise, they'll stack. You'll need some extra hacks for IE 6 (maybe 7 too) because it doesn't support inline-block.

Create multi-column layout with div is very simple but you should pay attention to the followings:

  • Sum of width of element column (including margin and padding) must < 100% (or width of the main column in pixel).
  • Using float:left (or right) to ensure the column appear side-by-side
  • Using a clear element to ensure the margin attribute of below elements

Example:

  <div id="main">
    <div class="col 1st-col">
    </div>
    <div class="col 2nd-col">
    </div>
    ...
    <div class="clr"></div>
  </div>

.col {float: left;} .1st-col {width: 30%; margin-left: 1%} ....

.clr {background: url('empty.gif');} /* empty.gif is a gif image (1px x 1px transparent) */

This surely works on every browser. Div .clr to fix the height of div.main in FF, Chrome, IE6. The attribute display: inline-block doesn't work in IE.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!