防止表格向下推动浮动左边的div

时间:2014-10-01 01:36:35

标签: css

我有两个浮动:左边的div设计用于从左到右堆叠,一个是经典的左导航并且声明了固定的宽度。另一个设计用于跨越浏览器宽度的其余部分并填充剩余宽度的100%。目前它没有本地或任何js / jQuery声明的宽度。

问题出现在第二个div中有一个表,它有大约10列表格结果,其中一些是较长的文本。一旦表格单元格的累积文本将表格宽度推到其所在的div的大小,div就会弹出左侧导航。

基本上是否有任何策略"告诉表格"它不会扩展到比父div更宽的范围,而是单元格中的文本将换行?我希望不必以任何方式使用JS。

<div id="container">
    <div id="leftNav" style="width:250px;">
    left<br>nav<br>here<br>        
    </div>
    <div id="mainContent">
        <table>
            <tr><td>about</td><td>10</td><td>Columns and they can contain sentences of text as well, but I'd like to not have the table push the div it's in down below the left nav div.  This illustrates that point!</td></tr>
        </table>
    </div>
</div>

和css:

#container{
    width:100%;
}
#leftNav{
    float:left;
    width:250px;
    border:1px solid #ccc;
    padding:15px;
}
#mainContent{
    float:left;
    background-color:aliceblue;
}
/* nothing more*/

2 个答案:

答案 0 :(得分:0)

我会使用display:table进行此布局。主要的好处是,无论内容宽度如何,列都将始终排列。

  • html,body { height: 100%; }<body>

  • 的子元素启用百分比高度
  • 容器已获得display: table

  • 这两列提供了display: table-cell

  • 左栏的宽度是固定的,右栏没有宽度

可能的缺点 - display: table兼容IE8 +

Read more about the display values on the MDN

CSS / HTML / Demo

&#13;
&#13;
* {
  margin: 0;
  padding: 0;
}
html,
body {
  height: 100%;
}
#container {
  width: 100%;
  display: table;
  height: 100%;
}
#leftNav {
  display: table-cell;
  vertical-align: top;
  width: 250px;
  border: 1px solid #ccc;
  padding: 15px;
}
#mainContent {
  display: table-cell;
  vertical-align: top;
  background-color: aliceblue;
}
/* nothing more*/
&#13;
<div id="container">
  <div id="leftNav">left
    <br>nav
    <br>here
    <br>
  </div>
  <div id="mainContent">
    <table>
      <tr>
        <td>about</td>
        <td>10</td>
        <td>Columns and they can contain sentences of text as well, but I'd like to not have the table push the div it's in down below the left nav div. This illustrates that point!</td>
      </tr>
    </table>
  </div>
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

将两个父div元素显示为内联表,该表将被视为子表并假设表符合一致行为。要使单元格值完全符合单元格的宽度,可以使用word-break: break-all;,这样可以在需要时为内联字符提供显示和中断。

div {
    display: inline-table;
    word-break: break-all;
    width: 40%;
}
<div>
  <p>Hello World</p>
</div>

<div>
  <table>
    <tr>
      <td>Table</td>
      <td>Table</td>
      <td>Table</td>
      <td>Table</td>
      <td>Table</td>
      <td>Table</td>
      <td>Table</td>
      <td>Table</td>
      <td>Table</td>
    </tr>
  </table>
</div>