首页 > 解决方案 > 如果它不适合,防止 div 跳转到下一行

问题描述

有什么办法可以防止 div3 被换行到下一行,而不是垂直滚动做水平?

<table>
<tr>

  <td>td1</td>

  <td>
    <div class="container">
        <div class="inner">div1</div>
        <div class="inner">div2</div>
        <div class="inner">div3</div>
    </div>
  </td>

</tr>
</table>


table { width: 400px; height: 100px; }
td { width: 50%; border: 1px solid gray; }

div.container { height: 100px; width: 100%; background: red; overflow-x: scroll; }

div.inner { height: 100px; width: 80px; display: block; float: left; background: blue; color: #fff; }

jsfiddle 示例

标签: css

解决方案


使用浮动,您不能在水平轴上滚动,因为如果浮动元素无法容纳在剩余空间中,它将落到下一行。

所以我们必须将 div 视为内联级别块并设置white-space:nowrap为防止 div 中断到下一行。

table {
  width: 400px;
  height: 100px;
  table-layout: fixed;
}

td {
  width: 50%;
  border: 1px solid gray;
}

div.container {
  height: 100px;
  width: 100%;
  background: red;
  overflow-x: scroll;
  /* added */
  white-space: nowrap;
  /* to remove space between divs */
  font-size: 0;
}

div.inner {
  height: 100px;
  width: 80px;
  background: blue;
  color: #fff;
  
  /*display: block; removed */
  /*float: left; removed */

  
  /* added */
  display: inline-block;
  
  /* because font size in inherited it will be set to 0
     but we want text to apear 
  */
  font-size: 16px;
}
<table>
  <tr>
    <td>td1</td>
    <td>
      <div class="container">
        <div class="inner">div1</div>
        <div class="inner">div2</div>
        <div class="inner">div3</div>
      </div>
    </td>
  </tr>
</table>


推荐阅读