html - 对 div 标签内的 span 元素应用边距和在 div 标签内应用边距有什么区别?

标签 html css

<分区>

.case1 {
  margin-bottom: 10px;
}
.case2 span {
  margin-bottom: 10px;
}
<div class="case1">
  <span>something</span>
</div>
<div class="case2">
  <span>something</span>
</div>

如果按如下方式应用 css,您在屏幕上看到的结果是一样的。那么,这两种方法中哪一种是最佳实践,为什么?

  • 谢谢回答。如果它是 p 元素而不是 span 元素,则结果很可能是相同的。这种情况下的最佳做法是什么?

最佳答案

<div>的和<p>例如是 Block Level可以占用所有边距的元素。 <span>不能,因为它是 Inline element仅在水平方向占用边距。

来自 W3 :

Margin properties specify the width of the margin area of a box. The 'margin' shorthand property sets the margin for all four sides while the other margin properties only set their respective side. These properties apply to all elements, but vertical margins will not have any effect on non-replaced inline elements.

可以设置display: inline-block;在你的 span使其成为 block 级。

.case1 {
  margin-bottom: 10px;
}

.case2 span {
  margin-bottom: 10px;
  margin-top: 20px; /* margin doesn't work */
  color: hotpink;
}

.case3 span {
  display: inline-block; /* made it block-level, margin works */
  margin-top: 40px;
  color: blue;
}
<div class="case1">
  <span>something</span>
</div>


<div class="case2">
  <span>something</span>
</div>

<div class="case3">
  <span>something</span>
</div>

关于html - 对 div 标签内的 span 元素应用边距和在 div 标签内应用边距有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72363725/

相关文章:

css - Viewport 100% height 不是 div 100% height,为什么?

html - 为什么 OnChange 在 Formik 中使用时不起作用?

jquery - 禁用父 jquery 上的点击事件

javascript - 附加到 JQuery 中的值

javascript - 如何计算单击的 donut 元素的中点与负 y 轴之间的 Angular

对话框中的 jQuery 选项卡小部件 : display error

jquery - 如何使用 Typeahead 和 Bloodhound 启用多属性搜索?

html - 带有文本的 SVG 周围的 IE/Edge 链接移动文本

javascript - 找不到类型为 '[object Object]' 的不同支持对象 'object' ,但它已经是一个数组

html - 创建一个导航栏,使用完整空间(css)的元素