布局更改取决于窗口小部件中的帖子数量

时间:2013-01-15 22:24:00

标签: css wordpress widget wordpress-theming

好的,所以我会尽力解释这个问题。我创建了一个小部件,它将根据类别从主页上的帖子中提取特色图像。现在它拉了4个帖子。我想有选择拉入2,3,4或6个帖子。我还想根据有多少帖子更改布局。是否可以只显示2,3,4或6个帖子,我将如何根据发布的帖子数量更改布局。我认为它会引用css中的每个帖子的容器类或类似的东西。任何链接,教程或建议将不胜感激! 谢谢, - 迈克尔

1 个答案:

答案 0 :(得分:0)

纯CSS

这提供了一种CSS3方法来实现你想要的东西,同时回归到CSS2。基本上,你有一个包装器来定位你的帖子项目,这将是直接在该包装器中的唯一孩子(或者,至少是特定“标签”类型的唯一孩子,这里是div)。如下所示,只有孩子的数量可以是2,3,4或6(根据您的要求)。

简单HTML (这不一定是div个元素;只是说明了)

<div class="postWrapper">
  <div>This is a post</div>
  <div>This is the second post</div>
</div>

设置默认CSS2

对于IE7 / 8,这将是默认显示,无论这两个浏览器中显示了多少帖子,使用此选择器:

.postWrapper > div { ... }

设置Fancy CSS3

这是根据帖子数量进行的,并将在所有CSS3浏览器中显示。它按以下顺序使用 这一系列选择器: (我们使用级联在这里有优势):

.postWrapper > div:nth-last-of-type(2),
.postWrapper > div:nth-last-of-type(2) ~ div {
   ... your two display css ...
}

.postWrapper > div:nth-last-of-type(3),
.postWrapper > div:nth-last-of-type(3) ~ div {
   ... your three display css ...
}

.postWrapper > div:nth-last-of-type(4),
.postWrapper > div:nth-last-of-type(4) ~ div {
   ... your four display css ...
}

.postWrapper > div:nth-last-of-type(6),
.postWrapper > div:nth-last-of-type(6) ~ div {
   ... your six display css ...
}

这样做是利用:nth-last-of-type()选择器“向后计数”包装器子div的数量,将样式应用于div,然后使用通用兄弟组合{ {1}}设置~中所有其他div的样式(首先是{理论上的} .postWrapper。它使用div对前两个执行此操作,但如果包装器包含三个,则使用:nth-last-of-type(2)的下一组选择器将覆盖先前的:nth-last-of-type(3)选择器,依此类推。通过这种方式,通过级联中的一系列重写css,我们更改了post元素数量的设置。

您可以在in this fiddle中查看此技术的示例以供说明之用。

注意:因为我们使用级联覆盖, 所以必须确保处理以前设置的任何css 。在我的小提琴示例中,请注意我如何将(2)放在一组四个上,但之后我将其删除为一组六个。如果我在第六组中没有提到margin(也就是说,没有覆盖),则六组中的元素3-6(但不是1-2)将基于之前的设置仍然应用了余量对于四人小组。