Three-column variable width CSS page layout, centr

2019-03-04 17:51发布

There is a plethora of CSS column layout information, but it all seems to rely on at least some of the columns having a fixed width (or percentage) which the others can then be based off.

What I'm trying to accomplish is a three-column layout, with the left and right columns being variable width (they could have anything in them) but being stuck to the left and right respectively. The centre column then should expand to take up any remaining space between them. I.e. if the right column has nothing in it, the centre column would then expand to the right of the screen.

Here's a quick shop to demonstrate:

Three-column example

标签: html css layout
2条回答
冷血范
2楼-- · 2019-03-04 18:43

You can (ab)use tables to help you out with this sort of layout. The basic idea is to set a table width to 100% (or a fixed value if you prefer), one column width to 100%, and let CSS determine how much space the other cells need. Here's a quick JSFiddle:

jsFiddle

The CSS is basically:

table {
    width: 100%;
}

td.b {
    /* Middle element that expands. */
    background-color: #efe8e1;
    width: 100%;
}

Notes:

  • Pretty simple!
  • If you end up with any horizontal overflow in the middle cell, tables have this weird habit of increasing the width of the table no matter what you set overflow to. Getting overflow scrolling to properly work with just the middle column is somewhere between a total pain and impossible. You can try making the td position: relative and have position: absolute div inside, but if I recall correctly, this doesn't work in IE8 in standards mode.
  • Tested on recent versions of Firefox/Safari/Chrome on desktop, and fuzzy memory indicates the non-scroll version of this trick works fine on IE7+. Reality may vary. :)
  • If you are thinking "ugh tables," you can use display: table, table-row, and table-cell to accomplish this too.
  • This trick works well with vertical expansion too!
  • It's a table, so the columns will stay the same height.
查看更多
Viruses.
3楼-- · 2019-03-04 18:45

If you don't mind to put the center element after left and right columns you could do something like this:

<div class="left"></div>
<div class="right"></div>
<div class="center"></div>

Just float the side elements, and for the middle one just add an overflow (could be hidden or scroll).

.left {
  float: left;
}

.right {
  float: right;
}

.center {
  overflow: hidden;
}

Here's the fiddle:

jsFiddle

查看更多
登录 后发表回答