CSS 删除第一个/最后一个元素的边距

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了CSS 删除第一个/最后一个元素的边距相关的知识,希望对你有一定的参考价值。

/* It can sometimes be desirable to remove the top or left margin from the first element in a container. Likewise, the right or bottom margin from the last element in a container. You can do this by manually applying classes to the HTML: */

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

/* The "top"/"bottom" zeroing being useful with a vertical stack of elements, "left"/"right" zeroing being useful for horizontal rows (in general). But... this method is dependent on you adding classes to the HTML yourself. Pseudo-selectors can be a better less intrusive way to go: */

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

/* You may want to replace the * with more specific selectors as per your needs.
"Every Third", etc. 

Lets say you had a floated block of 9 elements, 3 by 3. It's very common that you might need to remove the right margin from the 3rd, 6th, and 9th items. The nth-child pseudo-selector might be able to help there: */

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

/* The equation there, 3n+3, works like this:

(3x0)+3 = 3
(3x1)+3 = 6
(3x2)+3 = 9
etc.

jQuery

jQuery uses CSS3 selectors, which includes :first-child, :last-child, and :nth-child(). This means that in browsers with don't or don't fully support these selectors, they WILL work in jQuery, so you can substitute the CSS support with JavaScript support. For example: */

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

/* Browser support

:first-child and :last-child works in the latest release from all major browsers, but not in IE 6. :first-child is supported in IE 7+. :nth-child works in Safari 3+, Firefox 3.5+, and Chrome 1+, but still doesn't work in IE8. */

以上是关于CSS 删除第一个/最后一个元素的边距的主要内容,如果未能解决你的问题,请参考以下文章

如何删除正文周围的边距空间或清除默认 CSS 样式

带有 css 邻接选择器的响应式 flexbox 设计

在我的RecyclerView元素中,最后一个元素上下的边距不正确。

CSS 如果元素可见,则更改正文边距大小

RecyclerView 中最后一个子项的边距/填充

有没有办法为“除第一个/最后一个之外的所有元素”指定CSS简写?