【问题标题】:Is there any way to do this HTML layout without using tables?有没有办法在不使用表格的情况下进行这种 HTML 布局?
【发布时间】:2015-07-20 13:16:48
【问题描述】:

我正在开发一个内容非常动态的网站,该网站需要重排并适应不断变化的内容。主要要求之一是有一个页眉和页脚(也有不同长度和高度的动态内容),并且它们之间的内容总是占据它们之间剩余的任何空间。

对于表格,这很简单:

<table>
  <tr><td>Header</td></tr>
  <tr class="content"><td>Content</td></tr>
  <tr><td>Footer</td></tr>
</table>
table { height: 100%; }
tr.content { height: 100%; }

将这样的表格粘贴到任何容器中(包括视口,如果我们正在谈论顶级页面布局),就是这样,满足要求,完成工作。

但在我的一生中,我似乎无法找到使用 CSS 实现此目的的方法。我会认为,自从我第一次开始推动“整个 HTML 的东西”以来的 15 年多的时间里,像调整与其他事物相关的大小这样一个基本的事情到现在已经被提炼到近乎完美的程度,但它似乎并没有就这样吧。

我错过了什么吗?使用表格来布局页面感觉非常错误(当它到达内容的子表格时更是如此),但如果唯一的其他选择是 JavaScript,那么我宁愿回到 90 年代的 HTML。

这是一个说明我需要什么的 Codepen,通过上面显示的 HTML+CSS 实现:http://codepen.io/modo_lv/pen/PqBrRy?editors=110

【问题讨论】:

标签: html css


【解决方案1】:

这里有两个选项:

  1. 使用divsinstead of tables并使用表格布局CSS,例如

    display: table; display: table-row; display: table-cell;

  2. 使用Flexbox

【讨论】:

  • 在 display:table 中使用 div 基本上是一样的——你仍然使用无关的标签来指定布局。他们叫什么几乎没有什么区别。至于 Flexbox——现在 我一直缺少的东西。上次我听说“flex”是,正如我被引导相信的那样,IE 实现正确的 CSS 布局的尝试失败并最终放弃了。谢谢,我去看看。
【解决方案2】:

正如 Paul Redmond 所提到的......flexbox 同样微不足道

div {
  border: 1px solid grey;
  margin: 25px;
}
.container {
  height: 250px;
  width: 350px;
  display: flex;
  flex-direction: column;
}
header,
footer {
  flex: 0 0 auto;
  background: lightgrey;
}
main {
  flex-grow: 1;
  background: lightblue;
}
<div class="container">
  <header>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Sed, ab.</header>
  <main></main>
  <footer>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Esse quidem similique voluptates! A libero accusantium ut, autem ad eos natus accusamus alias ab, velit labore!</footer>
</div>

Codepen Demo

【讨论】:

    【解决方案3】:

    键入以下代码并将其保存为 .html 格式。我想它会对你有所帮助。

    <!DOCTYPE html>
    <html>
    <head>
        <title></title>
    </head>
    
    <body>
        <style>
    .div1 {
        border: 3px solid #052d31;
        position: relative;
        clear: left;
        float: left;
        margin: 3px;
        }
       </style>
    
        <div class="div1">
            <p>change this text the div will resize dynamically</p>
        </div>
    
        <div class="div1">
            <p>change this text</p>
        </div>
    </body>
    </html>
    

    【讨论】:

      猜你喜欢
      • 2010-10-06
      • 1970-01-01
      • 1970-01-01
      • 2022-11-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-02
      • 1970-01-01
      相关资源
      最近更新 更多