有时可能需要从容器中的第一个元素中删除顶部或左边距。 同样,容器中最后一个元素的右边距或底部距。 您可以通过将类手动应用于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个元素组成的浮动块,其中3个元素乘以3个元素。这很常见,您可能需要从第3、6和9个项目中删除正确的边距。 第n个子级伪选择器可以在此提供帮助:
* > :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中工作,因此您可以将CSS支持替换为JavaScript支持。 例如:
$("* > :nth-child(3n+3)").css("margin-right", 0);
浏览器支持
:first-child和:last-child在所有主要浏览器的最新版本中均可使用,但在IE 6中不可用。:IE 7+中支持:first-child。 :nth-child可在Safari 3 +,Firefox 3.5+和Chrome 1+中使用,但在IE8中仍无法使用。
另请参阅David Oliver的文章 。
翻译自: https://css-tricks.com/snippets/css/remove-margins-first-element/