首页 > 解决方案 > 为什么span元素的上半部分覆盖了文字而下半部分不覆盖

问题描述

以下代码说明了我的问题。

span {
    margin: 20px;
    padding: 20px;
    width: 80px;
    height: 50px;
    background-color: lightblue;
    border: 2px solid blue;
  }
p {
    width: 300px;
}
<p>
I am a paragraph and this is a <span>span</span> inside that paragraph. A span is an inline element and so does not respect width and height.
</p>

'paragraph'我们可以看到 span 元素的上半部分覆盖了文本,而下半部分'span is an'没有

代码笔网址在这里

标签: htmlcss

解决方案


这是因为文件的逐行执行。position:relative为它设置span将在其他元素之上。

span {
  margin: 20px;
  padding: 20px;
  width: 80px;
  height: 50px;
  background-color: red;
  border: 2px solid blue;
  position: relative;
}
p{
  width:300px;
}
<p>
    I am a paragraph and this is a <span>span</span> inside that paragraph. A span is an inline element and so does not respect width and height.
</p>     


推荐阅读