缺少单元格的 CSS 表格布局

标签 css html tablelayout

我有来自外部来源的 HTML 内容要使用。它带有 div 标记,看起来有点像这样:

<!DOCTYPE html>
<html>
  <head>
    <title>Example</title>
    <link rel="stylesheet" href="mycss.css" type="text/css"/>
  </head>
  <body>
    <div class="book">
      <div class="author">Author 1</div>
      <div class="title">Title 1</div>
      <div class="publisher">Publisher</div>
      <div class="year">2012</div>
    </div>
    <div class="book">
      <div class="author">Author 2</div>
      <div class="title">Title 2</div>
      <div class="year">2013</div>
    </div>
    <div class="book">
      <div class="author">Author 3</div>
      <div class="title">Title 3</div>
      <div class="publisher">Publisher</div>
    </div>
  </body>
</html>

现在,它想使用 CSS 在表格布局中显示它,每行交替使用颜色。有点像这样:

body {
  display: table;
  width: 100%;
}

.book {
  display: table-row;
}

.book:nth-child(even) {
  background: #FFF;
}

.book:nth-child(odd) {
  background: #DDD;
}

.author, .title, .publisher, .year {
  display: table-cell;         
}

但是,这个解决方案的问题是,如您所见,HTML 中缺少一些 div,但我想完成以下操作:

  1. 将各种信息垂直对齐。换句话说,将上述示例中每篇出版物的年份显示在与出版商信息不同的列中。
  2. 让行颜色扩展到覆盖页面每一行的宽度。

当我有多个列时,这甚至可以仅使用 CSS 吗?

摆弄 - http://jsfiddle.net/sRJhs/

最佳答案

最终答案,这个效果最好:

.book:nth-child(even) {
    background: #FFF;
}

.book:nth-child(odd) {
    background: #DDD;
}

.book {
    display: block;
    float: left;
    position: relative;
    width: 100%;
}

.book div {
    float: left;
    left: 100%;
    overflow: hidden;
    position: relative;
    width: 25%;
}
.author{
    margin-left: -100%;
}
.title{
    margin-left: -75%;
}
.publisher{
    margin-left: -50%;
}
.year {
    margin-left: -25%;
}

新 fiddle - http://jsfiddle.net/sRJhs/17/

关于缺少单元格的 CSS 表格布局,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16893560/

相关文章:

html - Safari 中的顶部边距可移除,但 Firefox 中不可移除

java - 每行列数不同的 JTable

html - IE8 从 tbody 中排除列

html - float 容器的高度

html - 为什么图像(在 CSS 中)没有出现在我的 HTML 中?

html - 如何使 css pentagon 的::after 部分响应?

php - 制作一个仪表板,显示具有延迟的 IP 列表

css - 如何停止下拉菜单将我的页面内容向下推?

html - 将 <ul></ul> 嵌套在 <p></p> 中会创建两个段落。为什么?

android - 动态添加 TableRow 与 getMeasuredHeight/getHeight 的问题