移除首尾元素的边距

Avatar of Chris Coyier
Chris Coyier

有时需要移除容器中第一个元素的顶部或左侧边距。同样地,也可能需要移除容器中最后一个元素的右侧或底部边距。可以通过手动向HTML添加类来实现。

.first { margin-top: 0 !important; margin-left: 0 !important; }
.last { margin-bottom: 0 !important; margin-right: 0 !important; }

对于垂直排列的元素,将“顶部”/“底部”边距设为零很有用;对于水平排列的元素(一般情况下),将“左侧”/“右侧”边距设为零很有用。但是……这种方法依赖于您自己向HTML添加类。伪选择器可以提供一种更好的、侵入性更低的方式。

* > :first-child { margin-top: 0 !important; margin-left: 0 !important; }
* > :last-child { margin-bottom: 0 !important; margin-right: 0 !important; }

您可能需要根据需要将 * 替换为更具体的选择器。

“每隔三个”,等等。

假设您有 9 个浮动块元素,3x3 排列。您可能经常需要移除第 3、第 6 和第 9 个元素的右侧边距。`nth-child` 伪选择器可以帮助您实现这一点。

* > :nth-child(3n+3) { margin-right: 0; }

那里的等式 3n+3 的工作原理如下

(3×0)+3 = 3
(3×1)+3 = 6
(3×2)+3 = 9
等等。

jQuery

jQuery 使用 CSS3 选择器,包括 `:first-child`、`:last-child` 和 `:nth-child()`。这意味着在不支持或不完全支持这些选择器的浏览器中,它们在 jQuery 中仍然可以工作,因此您可以用 JavaScript 支持替换 CSS 支持。例如

$("* > :nth-child(3n+3)").css("margin-right", 0);

浏览器支持

`:first-child` 和 `:last-child` 在所有主要浏览器的最新版本中都能正常工作,但在 IE 6 中不行。`first-child` 在 IE 7+ 中受支持。`nth-child` 在 Safari 3+、Firefox 3.5+ 和 Chrome 1+ 中工作,但在 IE 8 中仍然无法使用。

另请参阅 David Oliver 的文章