浮动的任何替代方案:左?

时间:2018-05-11 20:54:00

标签: html css

我有一个蓝色表,它使用float:left和一个附在这个表上的黄色按钮,也使用float:left。

该按钮用于向表中添加列。但当我添加这么多列以使表到达窗口边缘时 - 整个布局中断并且按钮跳了下来:

enter image description here

是否可以这样做,而不是向下跳按钮保持在原位并出现水平滚动条?

蓝色表放在名为canvas的div容器中。然后我用:

.canvas {
  float: left;
}

并对齐左侧黄色按钮:

.addColumn {
   float: left;
}

这是我的working demo。忘记粘贴吧,对不起!

当整个结构到达窗口边缘时,有什么想法可以阻止按钮离开它的位置吗?

2 个答案:

答案 0 :(得分:1)

如果你可以修改标记,将整个构造包装到另一个元素中,将表按钮放在该元素中,并使用绝对定位。

如果您绝对需要旧的浏览器支持,则应使用此解决方案。请查看下面的另一个片段,其中包含更现代,更通用的方法。

.wrapper {
  position: relative;
  float: left;
  
  padding-right: 20px;
  padding-bottom: 20px;
  
  /* for demonstration purposes */
  background: red;
}

.wrapper table {
  /* for demonstration purposes */
  background: lime;
}

.wrapper button {
  position: absolute;
  width: 20px;
  height: 20px;
  
  /* for demonstration purposes */
  padding: 0;
}

.add-column {
  top: 0;
  right: 0;
}

.add-row {
  bottom: 0;
  left: 0;
}
content content content content content content content content content content content content content content content 

<div class="wrapper">
  <table>
    <tbody>
      <tr>
        <td>A</td>
        <td>B</td>
      </tr>
      <tr>
        <td>C</td>
        <td>D</td>
      </tr>
    </tbody>
  </table>
  <button class="add-column">+</button>
  <button class="add-row">+</button>
</div>

after content content content content content content content content content content content content

或者如果您更喜欢更现代的方法,可以使用CSS Grid Layout模块,它不需要硬编码按钮大小和填充:

.wrapper {
  float: left;
  
  display: grid;
  grid-template-rows: auto 1fr;
  grid-template-columns: auto 1fr;
  grid-template-areas:
    "table column"
    "row   .     ";
  justify-items: start;
  align-items: start;
  
  /* for demonstration purposes */
  background: red;
}

.wrapper table {
  grid-area: table;
  
  /* for demonstration purposes */
  background: lime;
}

.add-column {
  grid-area: column;
}

.add-row {
  grid-area: row;
}
content content content content content content content content content content content content content content content

<div class="wrapper">
  <table>
    <tbody>
      <tr>
        <td>A</td>
        <td>B</td>
      </tr>
      <tr>
        <td>C</td>
        <td>D</td>
      </tr>
    </tbody>
  </table>
  <button class="add-column">+</button>
  <button class="add-row">+</button>
</div>

after content content content content content content content content content content content content

我建议在绝对定位上使用网格方法,因为在后面你必须硬编码按钮的宽度和高度,并保证填充是相同的。

使用网格,它更干净,更灵敏。

当然,如果您absolutely need 100% browser support,那么您应该更喜欢position技术,并接受或规避其限制。

答案 1 :(得分:0)

尝试使用

display:flex;

在你的容器div中。这将解决问题,并不需要float:left属性。

还尝试查看flex-flow , align and justify items以了解更多组合。