html - 仅向第一个和第二个 div 添加边距

标签 html css css-selectors

我希望仅向第一个和第二个“页面”div 添加 10px 的底部边距。我应该将它添加到页面还是页面 block

http://codepen.io/anon/pen/RWYObw

<div class="rows first">
<div class="page">
<div class="page-block">
<div class="page-image"><a href="/cat1"><img alt="" src="mypic1.jpg"   style="width: 198px; height: 178px;"></a></div>

<div class="block-heading"><a href="/category1">category1</a></div>
</div>
</div>

<div class="page">
<div class="page-block">
<div class="page-image"><a href="/cat2"><img alt="" src="mypic2.jpg"  style="width: 201px; height: 178px;"></a></div>

<div class="block-heading"><a href="/category2">category2</a></div>
</div>
</div>

<div class="page">
<div class="page-block">
<div class="page-image"><a href="/cat3"><img alt="" src="mypic3.jpg"   style="width: 227px; height: 170px;"></a></div>

<div class="block-heading"><a href="/category3">category3</a></div>
</div>
</div>

<div class="page last">
<div class="page-block">
<div class="page-image"><a href="/cat4"><img alt="" src="mypic4.jpg" style="width: 201px; height: 178px;"></a></div>

<div class="block-heading"><a href="/category4">category4</a></div>
</div>
</div>
</div>

因此 cat1 和 cat2 可以添加一个间隙

最佳答案

您可以将 first-of-type 与作为相邻选择器的 + 一起使用。您也可以为此使用 nth-of-type

.page:first-of-type,
.page:first-of-type + div.page {
  margin-bottom: 10px;
}

Demo

nth-of-type() 在这里也很方便,

.page:nth-of-type(1),
.page:nth-of-type(2) {
  margin-bottom: 10px;
}

还有另一种方法可以实现此目的,但我建议您忽略它,因为它在很大程度上依赖于父子关系。

.row > div:nth-of-type(1),
.row > div:nth-of-type(2) {
  margin-bottom: 10px;
}

关于html - 仅向第一个和第二个 div 添加边距,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33565501/

相关文章:

PHP:Adobe Reader 无法打开使用 mpdf 创建的 PDF 文件

CSS 3D 转换 - 无法点击链接

html - 在样式链接图像的左侧垂直居中分隔线

css - 选择不在某些元素内的元素

html - 带有只读属性选择器的 Chrome 中的奇怪样式行为

javascript - 表格鼠标悬停

php - 当图像名称中包含连字符时,为什么我的背景图像在 CSS 中不起作用?

javascript - 如何动态调整 DIV 元素的宽度以适应其文本内容?

css - 是否可以仅使用 CSS 自动调整输入文本和文本区域的大小或自动增长?

css - CSS 选择器区分大小写吗?