0

The code below always show the image irrespective of a relative or absolute position

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title
    </title>
    <style>
        #h1 {
            position: relative;
            width: 250px;
            height: 76px;
            left: 0;
            top: 0;
            background: url("https://dummyimage.com/250x76/000/fff&text=Heading+1") no-repeat;
        }
    </style>
</head>
<body>
<h1 id="h1">Heading 1
</h1>
</body>
</html>

But this code after adding a span element only shows the image if the position is set to absolute. I can't understand why in the second code the image won't show when the position is relative. And what makes the image appear once the position is set to absolute.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title
    </title>
    <style>
        #h1 span {
            position: relative;
            width: 250px;
            height: 76px;
            left: 0;
            top: 0;
            background: url("https://dummyimage.com/250x76/000/fff&text=Heading+1") no-repeat;
        }
    </style>
</head>
<body>
<h1 id="h1">Heading 1
    <span>
      </span>
</h1>
</body>
</html>
silverkid
  • 9,291
  • 22
  • 66
  • 92
  • Do you need to add a comma between #h1 and span like: #h1, span { ...} –  Oct 10 '18 at 09:19
  • 1
    There is nothing inside the `span` so there's no width or height and therefore the background image won't show. Add some text in the `span` and you'll see the background image loads. – Daniel Williams Oct 10 '18 at 09:19
  • 1
    Just trying to understand something I did not expect what I accidentally stumbled upon to achieve text replacement with Image. My understanding of absolute and relative is not good enough yet. – silverkid Oct 10 '18 at 09:21
  • 3
    because span is inline and it become block when you add position absolute and height apply to only block – Temani Afif Oct 10 '18 at 09:21

0 Answers0