一聚教程网:一个值得你收藏的教程网站

热门教程

css/jquery实现移除HTML中最后和第一个元素的间距(margin)

时间:2022-06-25 08:58:40 编辑:袖梨 来源:一聚教程网

手动添加CLASS

有时候,我们需要移除一个列表元素中,最后一个和第一个元素的间距(margin)属性,你可以手动给他们设置CSS样式:

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

TOP/BOTTOM归零是一个有用的重叠布局技术,LEFT/RIGHT用于水平布局,但是这个方法依赖于你需要手动的添加CSS样式到HTML标签中,如果是动态生成的元素,设置起来会非常的麻烦,伪类选择器可能是一个更好的选择方法。

伪类

下面的CSS选择通过:first-child和:last-child选取第一个元素和最后元素,然后设置我们需要的样式。
* > :first-child { margin-top: 0 !important; margin-left: 0 !important; }
* > :last-child { margin-bottom: 0 !important; margin-right: 0 !important; }

你可能需要替换*为具体的元素标签,来满足你的项目需求。
索引等差元素
假如我们有一个图片的列表,3行3列的布局,需要去除第三个、第六个和第九个元素的右间距,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, and :nth-child()。这意味着在不或是浏览器不完全支持这些选择,他们将工作在jQuery的,所以你可以用javascript支持替代CSS支持。例如:
$("* > :nth-child(3n+3)").css("margin-right", 0);

浏览器的支持

:first-child and :last-child在所有主要浏览器的最新版本的作品,但不是在IE 6。:first-child是在IE 7 +支持。 :nth-child能在Safari 3、Firefox 3.5和Chrome 1 +上工作,但还不能工作在IE8。

热门栏目