【问题标题】:Set height of absolutely positioned <div> inside <td> to <table>'s height?将 <td> 内绝对定位的 <div> 的高度设置为 <table> 的高度?
【发布时间】:2013-05-05 21:02:40
【问题描述】:

我正在主要使用 D3.js(link 到功能示例)创建甘特图。甘特图有垂直网格线来分隔每一天的列(下图中右侧的列),整个table 有分隔每一行/项目的水平网格线。以下是生成图表的示例:

为了大幅减少创建的元素数量并提高性能,而不是为每个项目/日期地址创建一个表格单元格(这将创建 #rows * #days 元素),我选择简单地绘制那些垂直每天在标题单元格中使用一个绝对定位的div 的网格线。例如,在图片中,30311 等单元格每个都有一个绝对定位的div,我手动将其高度设置为表格的全高。图表的结构是这样的:

<table>
    <tr><td colspan="5"></td><td>2012-12-30 to ...</td> ... </tr>
    <tr>
        <td></td>
        <td>Est. Duration</td>
        <td>% Completed</td>
        <td>Est. Start Date</td>
        <td>Est. End Date</td>
        <td class="day-cell">
            <div class="inner">
                <div class="background" style="height: 260px;">30</div>
            </div>
        </td>
        <td class="day-cell">
            <div class="inner">
                <div class="background" style="height: 260px;">31</div>
            </div>
        </td>
        <td class="day-cell">
            <div class="inner">
                <div class="background" style="height: 260px;">1</div>
            </div>
        </td>
        ...
    </tr>
    <tr class="project-row">...</tr>
    <tr class="project-row">...</tr>
    ...
</table>

除了必须手动设置高度的最后一个警告之外,这非常有效。理想情况下,我希望能够将div.background 的高度设置为100% 参考整个表本身的高度,而不必使用JavaScript,尽管如果绝对有必要/不可能避免,我会承认。一旦您开始添加或删除项目行,这个问题就最相关/最明显(为了模拟这一点,我只是降低了下图中div 的高度):

上面代码中类的相关样式有:

  • div.inner - position: relative; width: 19px
  • div.background - position: absolute; top: -1px; left: -1px; right -1px; line-height: 24px

Again, here's a functioning example of the chart's HTML and CSS (JSBin)。到目前为止,我对解决方案的尝试包括将tableposition 设置为relative 以及各种类似的东西。我什至考虑过将高度设置为像9999px 这样荒谬的东西,并在桌子上设置overflow-y: hidden,但如果有的话,我更喜欢更清洁的解决方案。

【问题讨论】:

标签: html css


【解决方案1】:

哇,这是一个非常简单的解决方案,我希望我能简单地考虑一下。

table 设置为position: relative,从.inner 中删除定位,然后简单地从.background 中删除topleftright 样式并在其上设置height: 100%使其定位正确。

我猜原因是如果你绝对定位一个元素,默认情况下它会位于它本来应该是静态定位的位置。因此,我可以通过不摆弄topleftright(以便将其定位在单元格中的正确位置)来让div 位于正确的位置,然后设置@ 987654333@ 到 100%(现在相对于table 的高度),并设置divwidth

【讨论】:

    猜你喜欢
    • 2012-08-12
    • 2015-03-17
    • 1970-01-01
    • 1970-01-01
    • 2019-07-08
    • 1970-01-01
    • 2021-10-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多