两个div之间的空格

22

我的问题是我有两个(或更多)相同类别的

需要彼此间隔。然而,我不能直接使用外边距,因为最后或第一个元素也将应用外边距,这不是我想要的。

示例
- 绿色是我想要的空白
- 红色是我不想要的空白

由于我所能想到的唯一解决方案都很复杂/涉及硬编码值,所以我希望有人能够想出聪明、简单的解决这个问题的方法。

详细信息:有时这些

会单独存在,并且在极少数情况下会浮动。

对上述想法的任何建议或改进、任何新想法,或者只是一般性的帮助都将不胜感激;)


你真的不能使用margin-top和margin-bottom吗?还是它不起作用?Margin也应该适用于浮动。 - Sófka
5个回答

29

你可以尝试类似以下的代码:

h1{
   margin-bottom:<x>px;
}
div{
   margin-bottom:<y>px;
}
div:last-of-type{
   margin-bottom:0;
}

或者可以使用以下代码替代第一个 h1 规则:

div:first-of-type{
   margin-top:<x>px;
}

或者更好的是使用相邻兄弟选择器。使用以下选择器,您可以在一个规则中解决您的问题:

div + div{
   margin-bottom:<y>px;
}

分别地,h1 + div 会控制标题后的第一个 div,为您提供额外的样式选项。


9
如果您不需要支持IE6:
h1 {margin-bottom:20px;}
div + div {margin-top:10px;}

第二行代码在div之间添加了间距,但不会在第一个div之前或最后一个div之后添加间距。

5

为什么不使用边距?你可以对一个元素应用各种各样的边距,而不仅仅是整个周围的边距。

您应该使用CSS类,因为这是引用多个元素,并且您可以使用id对那些您想要特别不同的元素进行标识

例如:

<style>
.box { height: 50px; background: #0F0; width: 100%; margin-top: 10px; }
#first { margin-top: 20px; }
#second { background: #00F; }
h1.box { background: #F00; margin-bottom: 50px;  }
</style>

<h1 class="box">Hello World</h1>
<div class="box" id="first"></div>
<div class="box" id="second"></div>​

这里有一个jsfiddle示例:

参考资料:

(注:本文为机器翻译,仅供参考。)

2
元素本身没有任何有用的含义,当然除了分割之外。

最好的做法是给它们添加一个有意义的类名,并在CSS中设置它们的单独边距。

<h1>Important Title</h1>
<div class="testimonials">...</div>
<div class="footer">...</div>

h1 {margin-bottom: 0.1em;}
div.testimonials {margin-bottom: 0.2em;}
div.footer {margin-bottom: 0;}

0
一个稍微新一点的解决方案是将div放在一个容器中,该容器具有display:flexdisplay:grid属性,并使用gap CSS属性,这将仅在容器内部元素之间添加空格,而不是在前/后添加。

flex solution:

.wrapper {
    display: flex;
    flex-direction: column;
    gap: 20px;
}
header, footer {
    background: red;
    color: white;
}
<header>header</header>
<div class="wrapper">
    <div>section 1</div>
    <div>section 2</div>
    <div>section 3</div>
</div>
<footer>footer</footer>

grid solution:

.wrapper {
    display: grid;
    grid-template-columns: 1fr;
    gap: 20px;
}
header, footer {
    background: red;
    color: white;
}
<header>header</header>
<div class="wrapper">
    <div>section 1</div>
    <div>section 2</div>
    <div>section 3</div>
</div>
<footer>footer</footer>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接