教程集 www.jiaochengji.com
教程集 >  CSS教程  >  经典实例  >  正文 css/jquery实现移除HTML中最后和第一个元素的间距(margin)

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

发布时间:2020-05-07   编辑:jiaochengji.com
教程集为您提供css/jquery实现移除HTML中最后和第一个元素的间距(margin)等资源,欢迎您收藏本站,我们将为您提供最新的css/jquery实现移除HTML中最后和第一个元素的间距(margin)资源
下面一起来一个小编整理的css/jquery实现移除HTML中最后和第一个元素的间距(margin)例子,希望例子可以对各位朋友带来帮助.

手动添加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。

您可能感兴趣的文章:
css/jquery实现移除HTML中最后和第一个元素的间距(margin)
css中负Margin你不知道的秘密
css网页布局用Margin还是用Padding
jQuery设计思想完整篇
锋利的jQuery 要点归纳(二) jQuery中的DOM操作(下)
css margin属性兼容性分析
css中去除inline-block元素间间距多种方法分享
简单的jquery拖拽排序效果实现代码
jquery对dom的操作常用方法整理
css的选择器的详细介绍

[关闭]
~ ~