如果不合适,请防止div跳至下一行

时间:2019-10-26 15:43:55

标签: css

有什么方法可以防止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 example

3 个答案:

答案 0 :(得分:1)

如果仅需要3个div,并且正在使用引导程序,则可以执行以下操作:

<table>
<tr>

  <td>td1</td>

  <td>
    <div class="container">
        <div class="col-3">div1</div>
        <div class="col-3">div2</div>
        <div class="col-3">div3</div>
    </div>
  </td>

</tr>
</table>

css

div {
  display: inline-block;
}

js fiddle

bootstrap网格系统默认将每一行分为12列,您可能想查看一下它们的文档:grid system

答案 1 :(得分:1)

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

因此,我们必须将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>

答案 2 :(得分:0)

<br>添加到您的代码中:

<table>
<tr>

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

</tr>
</table>