你在哪里放你的CSS边距? [英] Where do you put your CSS Margins?
问题描述
当您想在HTML元素(使用CSS)之间添加空格时,您要将其附加到哪个元素?
When you want to add whitespace between HTML elements (using CSS), to which element do you attach it?
<body>
<h1>This is the heading</h1>
<p>This is a paragraph</p>
<h1>Here's another heading</h1>
<div>This is a footer</div>
</body>
现在,假设我想在这些元素之间有1em的空间,下面的最后一个div。
Now, say I wanted 1em of space between each of these elements, but none above the first h1 or below the last div. To which elements would I attach it?
显然,这之间没有真正的技术差异:
Obviously, there's no real technical difference between this:
h1, p { margin-bottom: 1em; }
...和此...
div { margin-top: 1em; }
p { margin-top: 1em; margin-bottom: 1em }
我感兴趣的是次要因素:
What I'm interested is secondary factors:
- 一致性
- 适用于所有情况
- 轻松/简单
- 易于进行更改
- Consistency
- Applicability to all situations
- Ease / Simplicity
- Ease of making changes
例如:在这种情况下,我会说第一个解决方案比第二个更好,因为它更简单;您只在单个属性定义中将margin-bottom附加到两个元素。但是,我正在寻找一个更通用的解决方案。每次我做CSS工作,我得到的感觉,有一个很好的经验规则应用...但我不知道是什么。
For example: in this particular scenario, I'd say that the first solution is better than the second, as it's simpler; you're only attaching a margin-bottom to two elements in a single property definition. However, I'm looking for a more general-purpose solution. Every time I do CSS work, I get the feeling that there's a good rule of thumb to apply... but I'm not sure what it is. Does anyone have a good argument?
推荐答案
当我希望元素在元素之前有空格时, next元素,然后在css中使用.last类来从最后一个元素中删除边距。
I tend to use a bottom margin on elements when I want them to have space before the next element, and then to use a ".last" class in the css to remove the margin from the last element.
<body>
<h1>This is the heading</h1>
<p>This is a paragraph</p>
<h1>Here's another heading</h1>
<div class="last">This is a footer</div>
</body>
div { margin-bottom: 1em; }
p { margin-bottom: 1em; }
h1 { margin-bottom: 1em; }
.last {margin-bottom: 0; }
在你的例子中,这可能不是作为页脚div很可能有它自己的类和特定的造型。
仍然是.last方法我使用为我工作,当我有一个接一个(段落和什么 - 不是)几个相同的元素。
当然,我从ElementsCSS框架中挑选了该技术。
In your example though, this probably isn't that applicable, as a footer div would most likely have it's own class and specific styling. Still the ".last" approach I used works for me when I have several identical elements one after the other (paragraphs and what-not). Of course, I cherry-picked the technique from the "Elements" CSS framework.
这篇关于你在哪里放你的CSS边距?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!