我有来自外部源的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,但我想完成以下任务:
当我有多个列时,这甚至可以仅使用CSS吗?
答案 0 :(得分:2)
最后的答案,这是最好的:
.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%;
}
答案 1 :(得分:1)
这是一个有效的jsFiddle:http://jsfiddle.net/6Rwn2/
您需要为没有值的单元格设置空值。 (例如,放一个空格
)
答案 2 :(得分:0)
为什么不在加载时对齐数据?
见这里http://jsfiddle.net/ryPPs/
$(document).ready(function() {
var emptyYearDiv = $('<div class="year">n/a</div>');
var emptyAuthorDiv = $('<div class="author">n/a</div>');
var emptyTitleDiv = $('<div class="title">n/a</div>');
var emptyPublisherDiv = $('<div class="publisher">n/a</div>');
var emptyYearDiv = $('<div class="year">n/a</div>');
$(".book:not(:has(div[class^=year]))").append(emptyYearDiv);
$(".book:not(:has(div[class^=title]))").append(emptyTitleDiv);
$(".book:not(:has(div[class^=publisher]))").append(emptyPublisherDiv);
$(".book:not(:has(div[class^=year]))").append(emptyYearDiv);
});