从表格布局更改为div布局

时间:2014-12-16 02:27:36

标签: html css layout

好吧,所以我知道使用表格进行布局是不礼貌的,所以我尝试使用DIV等,让自己完全陷入困境,无法实现我所需的布局 - 从而使用了一张桌子。 / p>

布局实际上相对简单,但似乎有一些功能使CSS(至少对我来说)有点棘手。

只有2行。顶行有两个宽度相等的单元格。它们包含文本,应自动调整大小到正确的高度。

另一行包含iframe。它应该是容器的整个宽度,并占据剩余的容器高度。

我尝试了一些方法,包括使用CSS如display:table-cell等,但是因为我的第二行需要colspan =“2”,这根本不起作用。使用浮动div似乎也不能很好地工作,因为如何获得我的第二行 - 我不想采用绝对定位,因为那时我必须假设顶行的固定高度

那些能让我走上正轨的CSS专家吗?

这是一个示例演示我目前使用表格(下面的jsfiddle链接)。

HTML ...

<div id="cont">
    <table>
        <tr height="1%">
            <td><p>How would you do this with DIVs / CSS?<br />
                Some text. Lorem ipsum dolor sit amet,
                consectetur adipiscing elit, sed do eiusmod
                </p></td>
            <td><p>Some more text.<br />
                    These two cells have indeterminate size.<br />
                    They should only take up the minimum height.
            </p></td>
        </tr>
        <tr>
            <td colspan="2">
                <div id="iframe">
                    An iframe will go here.<br />
                    I'm just using a div for 
                    illustrative purposes.
                </div>
            </td>        
        </tr>
    </table>
</div>            

CSS

#cont {
    position: absolute;
    left: 4px;
    right: 4px;
    top: 4px;
    bottom: 4px;
}

table {
    width: 100%;
    height: 100%;
}

td {
    vertical-align: top;
}

#iframe {
    width: 100%;
    height: 100%;
    border: 1px solid green;
}

http://jsfiddle.net/z8qum850/

1 个答案:

答案 0 :(得分:3)

使用CSS非常容易。类似下面的内容可以提供您的要求:

<强> HTML

<div id="wrapper">
  <div id="row1">
    <div id="first-cell"></div>
    <div id="second-cell"></div>
  </div>
  <div id="row2"></div>
</div>

<强> CSS

div {
  border:1px solid black;
}
#wrapper {
  height:auto;
  width:100%;
}
#row1 {
  display:table;
  width:100%;
}
#first-cell,#second-cell {
  display:table-cell;
  height:200px;
}
#row2 {
  width:100%;
  height:200px;
  display:block;
}

使用display:tabletable-cell,子div元素将自动填充宽度,但您需要使用包装器来保存它们。因此,如果要删除#wrapper元素上的宽度声明,则会折叠所有内容,因为子元素不知道要填充多少空间。这是显示代码结果的CodePen demo

相关问题