Home > Net >  Why does the top half of the span element cover the text and the bottom half does not
Why does the top half of the span element cover the text and the bottom half does not

Time:10-08

The following code states my problem.

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>

As we can see that the top half of the span element cover the text and the bottom half does not, specifically, the word 'paragraph' is obscured but 'span is an' is not

codepen url here

CodePudding user response:

That's because of the line by line execution of the file. set position:relative for span it will be on top of other elements.

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>     

CodePudding user response:

If you need to make the span at the top add these two lines to the span's CSS.

span  {
 position: relative;
}

span {
  margin: 20px;
  padding: 20px;
  background-color: red;
  border: 2px solid blue;
  z-index: 999;
  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>

And also remember that width and height doesn't work on inline elements. You can use inline-block if you want.

  • Related