css - Margin-Top 不适用于 span 元素?

标签 css margin html

谁能告诉我我的编码错误吗?一切正常,唯一的问题是顶部没有边距。

HTML:

<div id="contact_us"> <!-- BEGIN CONTACT US -->
  <span class="first_title">Contact</span>
  <span class="second_title">Us</span>
  <p class="content">For any questions whatsoever please contact us through the following e-mail address:</p></br></br>
  <p class="e-mail">info@e-mail.com</p></br></br></br></br>
  <p class="read_more"><a href="underconstruction.html">Read More</a></p>
</div> <!-- END CONTACT US -->

CSS:

span.first_title {
  margin-top: 20px;
  margin-left: 12px;
  font-weight: bold;
  font-size: 24px;
  color: #221461;
}

span.second_title {
  margin-top: 20px;
  font-weight: bold;
  font-size: 24px;
  color: #b8b2d4;
}   

最佳答案

div 不同,p 1Block Level可以在所有方面占用 margin 的元素,span2 不能,因为它是 Inline仅水平占据边距的元素。

来自 specification :

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.

Demo 1 (垂直 ​​margin 未应用,因为 spaninline 元素)

解决方案?制作你的 span 元素,display: inline-block;display: block;.

Demo 2

建议您使用 display: inline-block;,因为它将是 inline 以及 block。仅将其设置为 block 将导致您的元素呈现 on another line , 因为 block 级别元素占用页面上 100% 的水平空间,除非它们是 inline-block 或者它们是 floated leftright


1. Block Level Elements - MDN 来源

2。 Inline Elements - MDN 资源

关于css - Margin-Top 不适用于 span 元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11700985/

相关文章:

css - 960网格系统-嵌套网格有布局问题

html - 无法让 Div 并排呈现

android - listview - 以编程方式为 listview 的项目设置负边距

javascript - 包含的 HTML 模板中的 AngularJS id 属性

javascript - 如何使用 Safari 移动设备检测输入文件中被忽略的大文件

html - 图像的响应框(仅限 css)

javascript - 使 SVG 响应式缩放

html - 将我的基本 <div> 样式设置为包含 “overflow:auto” 会有不利影响吗?

css - 如何强制显示垂直滚动条?

html - 如何在不使用边距的情况下对齐页面中间的框?