Css利润率与利润率最低

ken*_*ken 33 css layout

如果您有一系列块元素,并且您希望在它们之间放置边距.

您更喜欢哪个,保证金最高或保证金最低价还是两者兼而有之?为什么?

sbl*_*ndy 32

取决于背景.但是,通常margin-top更好,因为您可以使用:first-child它来删除它.像这样:

div.block {
    margin-top: 10px;
}

div.block:first-child {
    margin-top: 0;
}
Run Code Online (Sandbox Code Playgroud)

这样,边距仅在块之间.

仅适用于更现代的浏览器.

  • 您的目标是IE 6及更早版本?无论你做什么,这都会让事情变得丑陋. (6认同)

Win*_*ith 16

我总是使用margin-bottom,这意味着在第一个元素之前没有不必要的空间.


aja*_*221 15

这里投票最多的答案有点过时了,因为它说 go 的好处margin-top是你可以使用:first-child(但从 2018 年开始,你可以将margin-bottom:last-child结合使用,并获得同等支持)。

然而,在这篇文章CSS: margin top vs bottom中详细解释了更喜欢带 :first-child 的 margin-top(用:last-child代替margin-bottom)。

基本上,它表示如果您在其他相似块之间有一个块,并且您希望该块的边距(顶部和底部)与其余块不同,您会遇到更多麻烦,因为没有简单的方法来选择继续的元素,但是使用相邻的兄弟选择器 (+)可以在不需要帮助类的情况下实现这一点:

在此处输入图片说明

使用带有 :first-child结构的margin-top ,为广告提供适当间距所需的 CSS 是:

article {
    margin-top: 2em;
}

article:first-child {
    margin-top: 0;
}

//space at the top of the Ad
.ad {
    margin-top: 1em;
}

//and to reduce space below the ad
.ad + article {
    margin-top: 1em;
}
Run Code Online (Sandbox Code Playgroud)


tho*_*son 11

另一种选择是使用+选择器结合margin-top:

.article + .article {
    margin-top: 10px;
}
Run Code Online (Sandbox Code Playgroud)

这将选择后一个元素,这意味着该规则根本不适用于第一个元素.元素上方或下方没有其他类,伪类或空格.